diff --git a/dotnet/v3.4/Ads/CreateRotationGroup.cs b/dotnet/v3.4/Ads/CreateRotationGroup.cs deleted file mode 100755 index bf6d9d8..0000000 --- a/dotnet/v3.4/Ads/CreateRotationGroup.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a rotation group ad in a given campaign. Start and - /// end date for the ad must be within campaign start and end dates. To - /// create creatives, run one of the Create*Creative.cs examples. To get - /// available placements, run GetPlacements.cs. - /// - class CreateRotationGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a rotation group ad in a given campaign." + - " Start and end date for the ad must be within campaign start and" + - " end dates. To create creatives, run one of the Create*Creative.cs" + - " examples. To get available placements, run GetPlacements.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateRotationGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long creativeId = long.Parse(_T("INSERT_CREATIVE_ID_HERE")); - long placementId = long.Parse(_T("INSERT_PLACEMENT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - String adName = _T("INSERT_AD_NAME_HERE"); - - // Retrieve the campaign. - Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute(); - - // Create a click-through URL. - ClickThroughUrl clickThroughUrl = new ClickThroughUrl(); - clickThroughUrl.DefaultLandingPage = true; - - // Create a creative assignment. - CreativeAssignment creativeAssignment = new CreativeAssignment(); - creativeAssignment.Active = true; - creativeAssignment.CreativeId = creativeId; - creativeAssignment.ClickThroughUrl = clickThroughUrl; - - // Create a placement assignment. - PlacementAssignment placementAssignment = new PlacementAssignment(); - placementAssignment.Active = true; - placementAssignment.PlacementId = placementId; - - // Create a creative rotation. - CreativeRotation creativeRotation = new CreativeRotation(); - creativeRotation.CreativeAssignments = new List() { - creativeAssignment - }; - - // Create a delivery schedule. - DeliverySchedule deliverySchedule = new DeliverySchedule(); - deliverySchedule.ImpressionRatio = 1; - deliverySchedule.Priority = "AD_PRIORITY_01"; - - DateTime startDate = DateTime.Now; - DateTime endDate = Convert.ToDateTime(campaign.EndDate); - - // Create a rotation group. - Ad rotationGroup = new Ad(); - rotationGroup.Active = true; - rotationGroup.CampaignId = campaignId; - rotationGroup.CreativeRotation = creativeRotation; - rotationGroup.DeliverySchedule = deliverySchedule; - rotationGroup.StartTime = startDate; - rotationGroup.EndTime = endDate; - rotationGroup.Name = adName; - rotationGroup.PlacementAssignments = new List() { - placementAssignment - }; - rotationGroup.Type = "AD_SERVING_STANDARD_AD"; - - // Insert the rotation group. - Ad result = service.Ads.Insert(rotationGroup, profileId).Execute(); - - // Display the new ad ID. - Console.WriteLine("Ad with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Ads/GetAds.cs b/dotnet/v3.4/Ads/GetAds.cs deleted file mode 100755 index 807b7c2..0000000 --- a/dotnet/v3.4/Ads/GetAds.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the name, ID and advertiser ID for every active ad - /// your DFA user profile can see. - /// - class GetAds : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the name, ID and advertiser ID for" + - " every active ad.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAds(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,ads(advertiserId,id,name)"; - - AdsListResponse result; - String nextPageToken = null; - - do { - // Create and execute the ad list request. - AdsResource.ListRequest request = service.Ads.List(profileId); - request.Active = true; - request.Fields = fields; - request.PageToken = nextPageToken; - result = request.Execute(); - - foreach (Ad ad in result.Ads) { - Console.WriteLine( - "Ad with ID {0} and name \"{1}\" is associated with advertiser" + - " ID {2}.", ad.Id, ad.Name, ad.AdvertiserId); - } - - // Update the next page token. - nextPageToken = result.NextPageToken; - } while (result.Ads.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Advertisers/AssignAdvertisersToAdvertiserGroup.cs b/dotnet/v3.4/Advertisers/AssignAdvertisersToAdvertiserGroup.cs deleted file mode 100755 index 24a0ae7..0000000 --- a/dotnet/v3.4/Advertisers/AssignAdvertisersToAdvertiserGroup.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example assigns an advertiser to an advertiser group. - /// - /// CAUTION: An advertiser that has campaigns associated with it cannot be removed from an - /// advertiser group once assigned. - /// - class AssignAdvertisersToAdvertiserGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example assigns an advertiser to an advertiser group." + - "\n\nCAUTION: An advertiser that has campaigns associated with it" + - " cannot be removed from an advertiser group once assigned.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AssignAdvertisersToAdvertiserGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long advertiserGroupId = long.Parse(_T("INSERT_ADVERTISER_GROUP_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Create the Advertiser and populate with the group ID to patch. - Advertiser advertiser = new Advertiser(); - advertiser.AdvertiserGroupId = advertiserGroupId; - - // Patch the existing advertiser. - Advertiser result = - service.Advertisers.Patch(advertiser, profileId, advertiserId).Execute(); - - // Print out the advertiser and advertiser group ID. - Console.WriteLine("Advertiser with ID {0} was assigned to advertiser" + - " group \"{1}\".", result.Id, result.AdvertiserGroupId); - } - } -} diff --git a/dotnet/v3.4/Advertisers/CreateAdvertiser.cs b/dotnet/v3.4/Advertisers/CreateAdvertiser.cs deleted file mode 100755 index bc78361..0000000 --- a/dotnet/v3.4/Advertisers/CreateAdvertiser.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an advertiser in a given DCM account. To get - /// advertisers, see GetAdvertisers.cs. - /// - class CreateAdvertiser : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an advertiser in a given DCM account. To" + - " get advertisers, see GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateAdvertiser(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String advertiserName = _T("INSERT_ADVERTISER_NAME_HERE"); - - // Create the advertiser structure. - Advertiser advertiser = new Advertiser(); - advertiser.Name = advertiserName; - advertiser.Status = "APPROVED"; - - // Create the advertiser. - Advertiser result = service.Advertisers.Insert(advertiser, profileId).Execute(); - - // Display the advertiser ID. - Console.WriteLine("Advertiser with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Advertisers/CreateAdvertiserGroup.cs b/dotnet/v3.4/Advertisers/CreateAdvertiserGroup.cs deleted file mode 100755 index 0f2b76f..0000000 --- a/dotnet/v3.4/Advertisers/CreateAdvertiserGroup.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an advertiser group. To get advertiser groups, see - /// GetAdvertiserGroups.cs. - /// - class CreateAdvertiserGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an advertiser group. To get advertiser" + - " groups, see GetAdvertiserGroups.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateAdvertiserGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String advertiserGroupName = _T("INSERT_ADVERTISER_GROUP_NAME_HERE"); - - // Create advertiser group structure. - AdvertiserGroup advertiserGroup = new AdvertiserGroup(); - advertiserGroup.Name = advertiserGroupName; - - // Create advertiser group. - AdvertiserGroup result = - service.AdvertiserGroups.Insert(advertiserGroup, profileId).Execute(); - - // Display advertiser group ID. - Console.WriteLine("Advertiser Group with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Advertisers/CreateAdvertiserLandingPage.cs b/dotnet/v3.4/Advertisers/CreateAdvertiserLandingPage.cs deleted file mode 100755 index b4bb43a..0000000 --- a/dotnet/v3.4/Advertisers/CreateAdvertiserLandingPage.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an advertiser landing page. - /// - class CreateAdvertiserLandingPage : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an advertiser landing page."; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateAdvertiserLandingPage(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String landingPageName = _T("INSERT_LANDING_PAGE_NAME_HERE"); - String landingPageUrl = _T("INSERT_LANDING_PAGE_URL_HERE"); - - // Create the landing page structure. - LandingPage landingPage = new LandingPage(); - landingPage.AdvertiserId = advertiserId; - landingPage.Archived = false; - landingPage.Name = landingPageName; - landingPage.Url = landingPageUrl; - - // Create the landing page. - LandingPage result = service.AdvertiserLandingPages.Insert(landingPage, profileId).Execute(); - - // Display the landing page ID. - Console.WriteLine("Advertiser landing page with ID {0} and name \"{1}\" was created.", - result.Id, result.Name); - } - } -} diff --git a/dotnet/v3.4/Advertisers/GetAdvertiserGroups.cs b/dotnet/v3.4/Advertisers/GetAdvertiserGroups.cs deleted file mode 100755 index aaa88a0..0000000 --- a/dotnet/v3.4/Advertisers/GetAdvertiserGroups.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all advertiser groups for the specified user - /// profile. - /// - class GetAdvertiserGroups : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all advertiser groups for the" + - " specified user profile.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAdvertiserGroups(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,advertiserGroups(id,name)"; - - // List all advertiser groups - AdvertiserGroupsResource.ListRequest request = - service.AdvertiserGroups.List(profileId); - request.Fields = fields; - AdvertiserGroupsListResponse result = request.Execute(); - - // Display advertiser group names and IDs - if (result.AdvertiserGroups.Any()) { - foreach (AdvertiserGroup group in result.AdvertiserGroups) { - Console.WriteLine("Advertiser Group with ID {0} and name \"{1}\"" + - " was found.", group.Id, group.Name); - } - } else { - Console.WriteLine("No advertiser groups found for your criteria."); - } - } - } -} diff --git a/dotnet/v3.4/Advertisers/GetAdvertiserLandingPages.cs b/dotnet/v3.4/Advertisers/GetAdvertiserLandingPages.cs deleted file mode 100755 index d417ae8..0000000 --- a/dotnet/v3.4/Advertisers/GetAdvertiserLandingPages.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; -using System.Collections.Generic; - -namespace DfaReporting.Samples { - /// - /// This example lists all landing pages for a specified advertiser. - /// - class GetAdvertiserLandingPages : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all landing pages for a specified advertiser."; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAdvertiserLandingPages(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,landingPages(id,name,url)"; - - AdvertiserLandingPagesListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser landing pages list request. - AdvertiserLandingPagesResource.ListRequest request = - service.AdvertiserLandingPages.List(profileId); - request.AdvertiserIds = new List() { advertiserId.ToString() }; - request.Fields = fields; - request.PageToken = nextPageToken; - result = request.Execute(); - - foreach (LandingPage landingPage in result.LandingPages) { - Console.WriteLine("Advertiser landing page with ID {0}, name \"{1}\", and " + - "URL {2} was found.", landingPage.Id, landingPage.Name, landingPage.Url); - } - - // Update the next page token. - nextPageToken = result.NextPageToken; - } while (result.LandingPages.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Advertisers/GetAdvertisers.cs b/dotnet/v3.4/Advertisers/GetAdvertisers.cs deleted file mode 100755 index a7df909..0000000 --- a/dotnet/v3.4/Advertisers/GetAdvertisers.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the name, ID and spotlight configuration ID for - /// every advertiser your DCM user profile can see. - /// - class GetAdvertisers : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the name, ID and spotlight" + - " configuration ID for every advertiser your DCM user profile can" + - " see.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAdvertisers(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,advertisers(id,floodlightConfigurationId,name)"; - - AdvertisersListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser list request. - AdvertisersResource.ListRequest request = service.Advertisers.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - result = request.Execute(); - - foreach (Advertiser advertiser in result.Advertisers) { - Console.WriteLine("Advertiser with ID {0}, name \"{1}\", and" + - " floodlight configuration ID {2} was found.", advertiser.Id, - advertiser.Name, advertiser.FloodlightConfigurationId); - } - - // Update the next page token. - nextPageToken = result.NextPageToken; - } while (result.Advertisers.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Auth/AuthenticateUsingServiceAccount.cs b/dotnet/v3.4/Auth/AuthenticateUsingServiceAccount.cs deleted file mode 100755 index 7b1926b..0000000 --- a/dotnet/v3.4/Auth/AuthenticateUsingServiceAccount.cs +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using Google.Apis.Auth.OAuth2; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; -using Google.Apis.Json; -using Google.Apis.Services; -using System; -using System.Collections.Generic; -using System.IO; - -namespace DfaReporting.Samples { - /// - /// This example demonstrates how to authenticate and make a basic request using a service - /// account. - /// - class AuthenticateUsingServiceAccount : SampleBase { - /// - /// The OAuth 2.0 scopes to request. - /// - private static readonly IEnumerable OAuthScopes = new[] { - DfareportingService.Scope.Dfareporting - }; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example demonstrates how to authenticate and make a basic request" + - " using a service account.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AuthenticateUsingServiceAccount(); - Console.WriteLine(codeExample.Description); - codeExample.Run(null); - } - - /// - /// Run the code example. - /// - /// Unused - public override void Run(DfareportingService service) { - string pathToJsonFile = _T("ENTER_PATH_TO_JSON_FILE_HERE"); - - // An optional Google account email to impersonate. Only applicable to service accounts which - // have enabled domain-wide delegation and wish to make API requests on behalf of an account - // within their domain. Setting this field will not allow you to impersonate a user from a - // domain you don't own (e.g., gmail.com). - string emailToImpersonate = _T(""); - - // Build service account credential. - ServiceAccountCredential credential = - getServiceAccountCredential(pathToJsonFile, emailToImpersonate); - - // Create a Dfareporting service object. - // - // Note: application name should be replaced with a value that identifies your application. - service = new DfareportingService( - new BaseClientService.Initializer { - HttpClientInitializer = credential, - ApplicationName = "C# service account sample" - } - ); - - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = service.UserProfiles.List().Execute(); - - foreach (UserProfile profile in profiles.Items) { - Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", - profile.ProfileId, profile.UserName); - } - } - - private ServiceAccountCredential getServiceAccountCredential(String pathToJsonFile, - String emailToImpersonate) { - // Load and deserialize credential parameters from the specified JSON file. - JsonCredentialParameters parameters; - using (Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) { - parameters = NewtonsoftJsonSerializer.Instance.Deserialize(json); - } - - // Create a credential initializer with the correct scopes. - ServiceAccountCredential.Initializer initializer = - new ServiceAccountCredential.Initializer(parameters.ClientEmail) { - Scopes = OAuthScopes - }; - - // Configure impersonation (if applicable). - if (!String.IsNullOrEmpty(emailToImpersonate)) { - initializer.User = emailToImpersonate; - } - - // Create a service account credential object using the deserialized private key. - ServiceAccountCredential credential = - new ServiceAccountCredential(initializer.FromPrivateKey(parameters.PrivateKey)); - - return credential; - } - } -} diff --git a/dotnet/v3.4/Auth/AuthenticateUsingUserAccount.cs b/dotnet/v3.4/Auth/AuthenticateUsingUserAccount.cs deleted file mode 100755 index 2d21e1b..0000000 --- a/dotnet/v3.4/Auth/AuthenticateUsingUserAccount.cs +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using Google.Apis.Auth.OAuth2; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; -using Google.Apis.Json; -using Google.Apis.Services; -using Google.Apis.Util.Store; -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace DfaReporting.Samples { - /// - /// This example demonstrates how to authenticate and make a basic request using a user account, - /// via the - /// installed application flow. - /// - class AuthenticateUsingUserAccount : SampleBase { - /// - /// The location where authorization credentials will be cached. - /// - private static readonly string DataStorePath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "DfaReporting.Auth.Sample"); - - /// - /// The OAuth 2.0 scopes to request. - /// - private static readonly IEnumerable OAuthScopes = new[] { - DfareportingService.Scope.Dfareporting - }; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example demonstrates how to authenticate and make a basic request using a" + - " user account, via the installed application flow.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AuthenticateUsingUserAccount(); - Console.WriteLine(codeExample.Description); - codeExample.Run(null); - } - - /// - /// Run the code example. - /// - /// Unused - public override void Run(DfareportingService service) { - string pathToJsonFile = _T("ENTER_PATH_TO_JSON_FILE_HERE"); - - // Build user account credential. - UserCredential credential = - getUserAccountCredential(pathToJsonFile, new FileDataStore(DataStorePath, true)); - - // Create a Dfareporting service object. - // - // Note: application name should be replaced with a value that identifies your application. - service = new DfareportingService( - new BaseClientService.Initializer { - HttpClientInitializer = credential, - ApplicationName = "C# installed app sample" - } - ); - - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = service.UserProfiles.List().Execute(); - - foreach (UserProfile profile in profiles.Items) { - Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", - profile.ProfileId, profile.UserName); - } - } - - private UserCredential getUserAccountCredential(String pathToJsonFile, IDataStore dataStore) { - // Load client secrets from the specified JSON file. - GoogleClientSecrets clientSecrets; - using(Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) { - clientSecrets = GoogleClientSecrets.Load(json); - } - - // Create an asynchronous authorization task. - // - // Note: providing a data store allows auth credentials to be cached, so they survive multiple - // runs of the application. This avoids prompting the user for authorization every time the - // access token expires, by remembering the refresh token. The "user" value is used to - // identify a specific set of credentials within the data store. You may provide different - // values here to persist credentials for multiple users to the same data store. - Task authorizationTask = GoogleWebAuthorizationBroker.AuthorizeAsync( - clientSecrets.Secrets, - OAuthScopes, - "user", - CancellationToken.None, - dataStore); - - // Authorize and persist credentials to the data store. - UserCredential credential = authorizationTask.Result; - - return credential; - } - } -} diff --git a/dotnet/v3.4/Campaigns/CreateCampaign.cs b/dotnet/v3.4/Campaigns/CreateCampaign.cs deleted file mode 100755 index 830d2a3..0000000 --- a/dotnet/v3.4/Campaigns/CreateCampaign.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; -using System.Collections.Generic; - -namespace DfaReporting.Samples { - /// - /// This example creates a campaign associated with a given advertiser. To - /// create an advertiser, run CreateAdvertiser.cs. - /// - class CreateCampaign : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a campaign associated with a given" + - " advertiser. To create an advertiser, run CreateAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCampaign(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String campaignName = _T("INSERT_CAMPAIGN_NAME_HERE"); - - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(service, profileId, advertiserId); - - // Create the campaign structure. - Campaign campaign = new Campaign(); - campaign.Name = campaignName; - campaign.AdvertiserId = advertiserId; - campaign.Archived = false; - campaign.DefaultLandingPageId = defaultLandingPage.Id; - - // Set the campaign start date. This example uses today's date. - campaign.StartDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now); - - // Set the campaign end date. This example uses one month from today's date. - campaign.EndDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now.AddMonths(1)); - - // Insert the campaign. - Campaign result = service.Campaigns.Insert(campaign, profileId).Execute(); - - // Display the new campaign ID. - Console.WriteLine("Campaign with ID {0} was created.", result.Id); - } - - private LandingPage getAdvertiserLandingPage(DfareportingService service, long profileId, - long advertiserId) { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesResource.ListRequest listRequest = - service.AdvertiserLandingPages.List(profileId); - listRequest.AdvertiserIds = new List() { advertiserId.ToString() }; - listRequest.MaxResults = 1; - - AdvertiserLandingPagesListResponse landingPages = listRequest.Execute(); - - if (landingPages.LandingPages == null || landingPages.LandingPages.Count == 0) { - throw new InvalidOperationException( - String.Format("No landing pages found for advertiser with ID {0}.", advertiserId)); - } - - return landingPages.LandingPages[0]; - } - } -} diff --git a/dotnet/v3.4/Campaigns/CreateCampaignEventTag.cs b/dotnet/v3.4/Campaigns/CreateCampaignEventTag.cs deleted file mode 100755 index ff2cb56..0000000 --- a/dotnet/v3.4/Campaigns/CreateCampaignEventTag.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an event tag for the specified campaign. - /// - class CreateCampaignEventTag : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an event tag for the specified campaign.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCampaignEventTag(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String eventTagName = _T("INSERT_EVENT_TAG_NAME_HERE"); - String eventTagUrl = _T("INSERT_EVENT_TAG_URL_HERE"); - - // Create the event tag structure. - EventTag eventTag = new EventTag(); - eventTag.CampaignId = campaignId; - eventTag.Name = eventTagName; - eventTag.Status = "ENABLED"; - eventTag.Type = "CLICK_THROUGH_EVENT_TAG"; - eventTag.Url = eventTagUrl; - - // Insert the campaign. - EventTag result = service.EventTags.Insert(eventTag, profileId).Execute(); - - // Display the new campaign ID. - Console.WriteLine("Event Tag with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Campaigns/GetCampaigns.cs b/dotnet/v3.4/Campaigns/GetCampaigns.cs deleted file mode 100755 index a6b9df6..0000000 --- a/dotnet/v3.4/Campaigns/GetCampaigns.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all existing campaigns for the specified user profile. - /// - class GetCampaigns : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all existing campaigns for the specified" + - " user profile.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCampaigns(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,campaigns(id,name)"; - - CampaignsListResponse campaigns; - String nextPageToken = null; - - do { - // Create and execute the campaigns list request. - CampaignsResource.ListRequest request = service.Campaigns.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - campaigns = request.Execute(); - - foreach (Campaign campaign in campaigns.Campaigns) { - Console.WriteLine("Campaign with ID {0} and name \"{1}\" was found.", - campaign.Id, campaign.Name); - } - - // Update the next page token. - nextPageToken = campaigns.NextPageToken; - } while (campaigns.Campaigns.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Conversions/InsertOfflineMobileConversion.cs b/dotnet/v3.4/Conversions/InsertOfflineMobileConversion.cs deleted file mode 100755 index fb6a43c..0000000 --- a/dotnet/v3.4/Conversions/InsertOfflineMobileConversion.cs +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example inserts an offline conversion attributed to a mobile device ID. - /// - class InsertOfflineMobileConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example inserts an offline conversion attributed to a mobile device ID.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new InsertOfflineMobileConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string conversionMobileId = _T("INSERT_CONVERSION_MOBILE_ID_HERE"); - - // Generate a timestamp in milliseconds since Unix epoch. - TimeSpan timeStamp = DateTime.UtcNow - new DateTime(1970, 1, 1); - long currentTimeInMilliseconds = (long) timeStamp.TotalMilliseconds; - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Create the conversion. - Conversion conversion = new Conversion(); - conversion.MobileDeviceId = conversionMobileId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = currentTimeInMilliseconds.ToString(); - conversion.TimestampMicros = currentTimeInMilliseconds * 1000; - - // Insert the conversion. - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.Conversions = new List() { conversion }; - - ConversionsBatchInsertResponse response = - service.Conversions.Batchinsert(request, profileId).Execute(); - - // Handle the batchinsert response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully inserted conversion for mobile device ID {0}.", - conversionMobileId); - } else { - Console.WriteLine("Error(s) inserting conversion for mobile device ID {0}:", - conversionMobileId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.4/Conversions/InsertOfflineUserConversion.cs b/dotnet/v3.4/Conversions/InsertOfflineUserConversion.cs deleted file mode 100755 index e5ffb76..0000000 --- a/dotnet/v3.4/Conversions/InsertOfflineUserConversion.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example inserts an offline conversion attributed to an encrypted user ID. - /// - class InsertOfflineUserConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example inserts an offline conversion attributed to an encrypted user" + - " ID.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new InsertOfflineUserConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long encryptionEntityId = long.Parse(_T("INSERT_ENCRYPTION_ENTITY_TYPE")); - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string conversionUserId = _T("INSERT_CONVERSION_USER_ID_HERE"); - string encryptionEntityType = _T("INSERT_ENCRYPTION_ENTITY_TYPE_HERE"); - string encryptionSource = _T("INSERT_ENCRYPTION_SOURCE_HERE"); - - // Generate a timestamp in milliseconds since Unix epoch. - TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1); - long currentTimeInMilliseconds = (long) timeSpan.TotalMilliseconds; - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Create the conversion. - Conversion conversion = new Conversion(); - conversion.EncryptedUserId = conversionUserId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = currentTimeInMilliseconds.ToString(); - conversion.TimestampMicros = currentTimeInMilliseconds * 1000; - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.EncryptionEntityId = encryptionEntityId; - encryptionInfo.EncryptionEntityType = encryptionEntityType; - encryptionInfo.EncryptionSource = encryptionSource; - - // Insert the conversion. - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.Conversions = new List() { conversion }; - request.EncryptionInfo = encryptionInfo; - - ConversionsBatchInsertResponse response = - service.Conversions.Batchinsert(request, profileId).Execute(); - - // Handle the batchinsert response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully inserted conversion for encrypted user ID {0}.", - conversionUserId); - } else { - Console.WriteLine("Error(s) inserting conversion for encrypted user ID {0}:", - conversionUserId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.4/Conversions/UpdateOfflineMobileConversion.cs b/dotnet/v3.4/Conversions/UpdateOfflineMobileConversion.cs deleted file mode 100755 index 6b98fad..0000000 --- a/dotnet/v3.4/Conversions/UpdateOfflineMobileConversion.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example updates an offline conversion attributed to a mobile device ID. To create a - /// conversion attributed to a mobile device ID, run InsertOfflineMobileConversion.cs. - /// - class UpdateOfflineMobileConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example updates an offline conversion attributed to a mobile device ID. " + - "To create a conversion attributed to a mobile device ID, run " + - "InsertOfflineMobileConversion.cs\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new UpdateOfflineMobileConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Values that identify the existing conversion. - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long conversionTimestamp = long.Parse(_T("INSERT_CONVERSION_TIMESTAMP_HERE")); - string conversionOrdinal = _T("INSERT_CONVERSION_ORDINAL_VALUE_HERE"); - string conversionMobileId = _T("INSERT_CONVERSION_MOBILE_ID_HERE"); - - // Values to update for the specified conversion. - long newQuantity = long.Parse(_T("INSERT_NEW_CONVERSION_QUANTITY_HERE")); - long newValue = long.Parse(_T("INSERT_NEW_CONVERSION_VALUE_HERE")); - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Construct the conversion object with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.MobileDeviceId = conversionMobileId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = conversionOrdinal; - conversion.TimestampMicros = conversionTimestamp; - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.Quantity = newQuantity; - conversion.Value = newValue; - - // Update the conversion. - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.Conversions = new List() { conversion }; - - ConversionsBatchUpdateResponse response = - service.Conversions.Batchupdate(request, profileId).Execute(); - - // Handle the batchupdate response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully updated conversion for mobile device ID {0}.", - conversionMobileId); - } else { - Console.WriteLine("Error(s) updating conversion for mobile device ID {0}:", - conversionMobileId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.4/Conversions/UpdateOfflineUserConversion.cs b/dotnet/v3.4/Conversions/UpdateOfflineUserConversion.cs deleted file mode 100755 index 9e3a946..0000000 --- a/dotnet/v3.4/Conversions/UpdateOfflineUserConversion.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example updates an offline conversion attributed to an encrypted user ID. To create a - /// conversion attributed to an excrypted user ID, run InsertOfflineUserConversion.cs. - /// - class UpdateOfflineUserConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example updates an offline conversion attributed to an encrypted user ID. " + - "To create a conversion attributed to an encrypted user ID, run " + - "InsertOfflineUserConversion.cs\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new UpdateOfflineUserConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Value that specify how the existing conversion is encrypted. - long encryptionEntityId = long.Parse(_T("INSERT_ENCRYPTION_ENTITY_TYPE")); - string encryptionEntityType = _T("INSERT_ENCRYPTION_ENTITY_TYPE_HERE"); - string encryptionSource = _T("INSERT_ENCRYPTION_SOURCE_HERE"); - - // Values that identify the existing conversion. - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long conversionTimestamp = long.Parse(_T("INSERT_CONVERSION_TIMESTAMP_HERE")); - string conversionOrdinal = _T("INSERT_CONVERSION_ORDINAL_VALUE_HERE"); - string conversionUserId = _T("INSERT_CONVERSION_USER_ID_HERE"); - - // Values to update for the specified conversion. - long newQuantity = long.Parse(_T("INSERT_NEW_CONVERSION_QUANTITY_HERE")); - long newValue = long.Parse(_T("INSERT_NEW_CONVERSION_VALUE_HERE")); - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Construct the conversion object with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.EncryptedUserId = conversionUserId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = conversionOrdinal; - conversion.TimestampMicros = conversionTimestamp; - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.Quantity = newQuantity; - conversion.Value = newValue; - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.EncryptionEntityId = encryptionEntityId; - encryptionInfo.EncryptionEntityType = encryptionEntityType; - encryptionInfo.EncryptionSource = encryptionSource; - - // Insert the conversion. - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.Conversions = new List() { conversion }; - request.EncryptionInfo = encryptionInfo; - - ConversionsBatchUpdateResponse response = - service.Conversions.Batchupdate(request, profileId).Execute(); - - // Handle the batchinsert response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully updated conversion for encrypted user ID {0}.", - conversionUserId); - } else { - Console.WriteLine("Error(s) updating conversion for encrypted user ID {0}:", - conversionUserId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.4/Creatives/Assets/CreativeAssetUtils.cs b/dotnet/v3.4/Creatives/Assets/CreativeAssetUtils.cs deleted file mode 100755 index 7788672..0000000 --- a/dotnet/v3.4/Creatives/Assets/CreativeAssetUtils.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.IO; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; -using Google.Apis.Upload; - -namespace DfaReporting.Samples { - class CreativeAssetUtils { - private static DfareportingService Service; - private static long ProfileId; - private static long AdvertiserId; - - public CreativeAssetUtils(DfareportingService service, long profileId, long advertiserId) { - AdvertiserId = advertiserId; - ProfileId = profileId; - Service = service; - } - - /// - /// Uploads a creative asset and associates it with the specified advertiser. - /// - /// The path to the asset file to be uploaded - /// The CreativeAssetId type of the asset - /// - /// A CreativeAssetMetadata object populated with the name of the asset after insert. - /// - public CreativeAssetMetadata uploadAsset(String assetFile, String assetType) { - // Prepare an input stream. - FileStream assetContent = new FileStream(assetFile, FileMode.Open, FileAccess.Read); - - // Create the creative asset ID and Metadata. - CreativeAssetId assetId = new CreativeAssetId(); - assetId.Name = Path.GetFileName(assetFile); - assetId.Type = assetType; - - CreativeAssetMetadata metaData = new CreativeAssetMetadata(); - metaData.AssetIdentifier = assetId; - - // Insert the creative. - String mimeType = determineMimeType(assetFile, assetType); - CreativeAssetsResource.InsertMediaUpload request = - Service.CreativeAssets.Insert(metaData, ProfileId, AdvertiserId, assetContent, mimeType); - - IUploadProgress progress = request.Upload(); - if (UploadStatus.Failed.Equals(progress.Status)) { - throw progress.Exception; - } - - // Display the new asset name. - Console.WriteLine("Creative asset was saved with name \"{0}\".", - request.ResponseBody.AssetIdentifier.Name); - return request.ResponseBody; - } - - private String determineMimeType(String assetFile, String assetType) { - switch (assetType) { - case "IMAGE": - case "HTML_IMAGE": - return "image/" + Path.GetExtension(assetFile); - case "VIDEO": - return "video/" + Path.GetExtension(assetFile); - default: - return "application/octet-stream"; - } - } - } -} diff --git a/dotnet/v3.4/Creatives/AssignCreativeToCampaign.cs b/dotnet/v3.4/Creatives/AssignCreativeToCampaign.cs deleted file mode 100755 index 4a23221..0000000 --- a/dotnet/v3.4/Creatives/AssignCreativeToCampaign.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example assigns a given creative to a given campaign. Note that both - /// the creative and campaign must be associated with the same advertiser. - /// - class AssignCreativeToCampaign : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example assigns a given creative to a given campaign." + - " Note that both the creative and campaign must be associated with" + - " the same advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AssignCreativeToCampaign(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long creativeId = long.Parse(_T("INSERT_CREATIVE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Create the campaign creative association structure. - CampaignCreativeAssociation association = new CampaignCreativeAssociation(); - association.CreativeId = creativeId; - - // Insert the association. - CampaignCreativeAssociation result = - service.CampaignCreativeAssociations.Insert(association, profileId, campaignId).Execute(); - - // Display a success message. - Console.WriteLine("Creative with ID {0} is now associated with campaign {1}.", - result.CreativeId, campaignId); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateCreativeField.cs b/dotnet/v3.4/Creatives/CreateCreativeField.cs deleted file mode 100755 index 99ed9d4..0000000 --- a/dotnet/v3.4/Creatives/CreateCreativeField.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a creative field associated with a given advertiser. - /// To get an advertiser ID, run GetAdvertisers.cs. - /// - class CreateCreativeField : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a creative field associated with a" + - " given advertiser. To get an advertiser ID, run" + - " GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCreativeField(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string creativeFieldName = _T("INSERT_CREATIVE_FIELD_NAME_HERE"); - - // Create the creative field. - CreativeField creativeField = new CreativeField(); - creativeField.Name = creativeFieldName; - creativeField.AdvertiserId = advertiserId; - - // Insert the creative field. - CreativeField result = - service.CreativeFields.Insert(creativeField, profileId).Execute(); - - // Display the new creative field ID. - Console.WriteLine("Creative field with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateCreativeFieldValue.cs b/dotnet/v3.4/Creatives/CreateCreativeFieldValue.cs deleted file mode 100755 index b2b4805..0000000 --- a/dotnet/v3.4/Creatives/CreateCreativeFieldValue.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a creative field value associated with a given - /// creative field. To get the creative field ID, run GetCreativeFields.java. - /// - class CreateCreativeFieldValue : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a creative field value associated with" + - " a given creative field. To get the creative field ID, run" + - " GetCreativeFields.java.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCreativeFieldValue(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long creativeFieldId = long.Parse(_T("INSERT_CREATIVE_FIELD_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string creativeFieldValueName = _T("INSERT_CREATIVE_FIELD_VALUE_NAME_HERE"); - - // Create the creative field value. - CreativeFieldValue creativeFieldValue = new CreativeFieldValue(); - creativeFieldValue.Value = creativeFieldValueName; - - // Insert the creative field value. - CreativeFieldValue result = service.CreativeFieldValues - .Insert(creativeFieldValue, profileId, creativeFieldId).Execute(); - - // Display the new creative field value ID. - Console.WriteLine("Creative field value with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateCreativeGroup.cs b/dotnet/v3.4/Creatives/CreateCreativeGroup.cs deleted file mode 100755 index 775e862..0000000 --- a/dotnet/v3.4/Creatives/CreateCreativeGroup.cs +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a creative group associated with a given advertiser. - /// To get an advertiser ID, run getAdvertisers.cs. Valid group numbers are - /// limited to 1 or 2. - /// - class CreateCreativeGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a creative group associated with a given" + - " advertiser. To get an advertiser ID, run getAdvertisers.cs. Valid" + - " group numbers are limited to 1 or 2.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCreativeGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - int groupNumber = int.Parse(_T("INSERT_GROUP_NUMBER_HERE")); - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string creativeGroupName = _T("INSERT_CREATIVE_GROUP_NAME_HERE"); - - // Create the creative group. - CreativeGroup creativeGroup = new CreativeGroup(); - creativeGroup.Name = creativeGroupName; - creativeGroup.GroupNumber = groupNumber; - creativeGroup.AdvertiserId = advertiserId; - - // Insert the creative group. - CreativeGroup result = - service.CreativeGroups.Insert(creativeGroup, profileId).Execute(); - - // Display the new creative group ID. - Console.WriteLine("Creative group with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateDisplayImageGalleryCreative.cs b/dotnet/v3.4/Creatives/CreateDisplayImageGalleryCreative.cs deleted file mode 100755 index 665d829..0000000 --- a/dotnet/v3.4/Creatives/CreateDisplayImageGalleryCreative.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates a display image - /// gallery creative associated with a given advertiser. To get a size ID, - /// run GetSize.cs. - /// - class CreateDisplayImageGalleryCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates a display" + - " image gallery creative associated with a given advertiser. To" + - " get a size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateDisplayImageGalleryCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string pathToImageAssetFile = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - string pathToImageAsset2File = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.AutoAdvanceImages = true; - creative.Name = "Test display image gallery creative"; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY_IMAGE_GALLERY"; - - // Upload the first image asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId imageAsset1Id = - assetUtils.uploadAsset(pathToImageAssetFile, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset1 = new CreativeAsset(); - imageAsset1.AssetIdentifier = imageAsset1Id; - imageAsset1.Role = "PRIMARY"; - - // Upload the second image asset. - CreativeAssetId imageAsset2Id = - assetUtils.uploadAsset(pathToImageAsset2File, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset2 = new CreativeAsset(); - imageAsset2.AssetIdentifier = imageAsset2Id; - imageAsset2.Role = "PRIMARY"; - - // Add the creative assets. - creative.CreativeAssets = new List() { imageAsset1, imageAsset2 }; - - // Create a click tag for the first image asset. - ClickTag clickTag1 = new ClickTag(); - clickTag1.Name = imageAsset1Id.Name; - clickTag1.EventName = imageAsset1Id.Name; - - // Create a click tag for the second image asset. - ClickTag clickTag2 = new ClickTag(); - clickTag2.Name = imageAsset2Id.Name; - clickTag2.EventName = imageAsset2Id.Name; - - // Add the click tags. - creative.ClickTags = new List() { clickTag1, clickTag2 }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Display image gallery creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateDisplayRedirectCreative.cs b/dotnet/v3.4/Creatives/CreateDisplayRedirectCreative.cs deleted file mode 100755 index 754dd1a..0000000 --- a/dotnet/v3.4/Creatives/CreateDisplayRedirectCreative.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a display redirect creative associated with a given - /// advertiser. To get a size ID, run GetSize.cs. - /// - class CreateDisplayRedirectCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a display redirect creative associated" + - " with a given advertiser. To get a size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateDisplayRedirectCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string imageUrl = _T("INSERT_IMAGE_URL_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test display redirect creative"; - creative.RedirectUrl = imageUrl; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY_REDIRECT"; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Display redirect creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateHTML5DisplayCreative.cs b/dotnet/v3.4/Creatives/CreateHTML5DisplayCreative.cs deleted file mode 100755 index f324437..0000000 --- a/dotnet/v3.4/Creatives/CreateHTML5DisplayCreative.cs +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an HTML5 display - /// creative associated with a given advertiser. To get a size ID, run - /// GetSize.cs. - /// - class CreateHTML5DisplayCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an HTML5" + - " display creative associated with a given advertiser. To get a" + - " size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateHTML5DisplayCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string pathToHtml5AssetFile = _T("INSERT_PATH_TO_HTML5_ASSET_FILE_HERE"); - string pathToImageAssetFile = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(service, profileId, advertiserId); - - // Create the creative structure. - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test HTML5 display creative"; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY"; - - // Upload the HTML5 asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId html5AssetId = - assetUtils.uploadAsset(pathToHtml5AssetFile, "HTML").AssetIdentifier; - - CreativeAsset html5Asset = new CreativeAsset(); - html5Asset.AssetIdentifier = html5AssetId; - html5Asset.Role = "PRIMARY"; - - // Upload the backup image asset. - CreativeAssetId imageAssetId = - assetUtils.uploadAsset(pathToImageAssetFile, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset = new CreativeAsset(); - imageAsset.AssetIdentifier = imageAssetId; - imageAsset.Role = "BACKUP_IMAGE"; - - // Add the creative assets. - creative.CreativeAssets = new List() { html5Asset, imageAsset }; - - // Configure the bacup image. - creative.BackupImageClickThroughUrl = new CreativeClickThroughUrl() { - LandingPageId = defaultLandingPage.Id - }; - creative.BackupImageReportingLabel = "backup"; - creative.BackupImageTargetWindow = new TargetWindow() { TargetWindowOption = "NEW_WINDOW" }; - - // Add a click tag. - ClickTag clickTag = new ClickTag(); - clickTag.Name = "clickTag"; - clickTag.EventName = "exit"; - clickTag.ClickThroughUrl = new CreativeClickThroughUrl() { - LandingPageId = defaultLandingPage.Id - }; - creative.ClickTags = new List() { clickTag }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("HTML5 display creative with ID {0} was created.", result.Id); - } - - private LandingPage getAdvertiserLandingPage(DfareportingService service, long profileId, - long advertiserId) { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesResource.ListRequest listRequest = - service.AdvertiserLandingPages.List(profileId); - listRequest.AdvertiserIds = new List() { advertiserId.ToString() }; - listRequest.MaxResults = 1; - - AdvertiserLandingPagesListResponse landingPages = listRequest.Execute(); - - if (landingPages.LandingPages == null || landingPages.LandingPages.Count == 0) { - throw new InvalidOperationException( - String.Format("No landing pages found for advertiser with ID {0}.", advertiserId)); - } - - return landingPages.LandingPages[0]; - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateImageDisplayCreative.cs b/dotnet/v3.4/Creatives/CreateImageDisplayCreative.cs deleted file mode 100755 index 5efdd47..0000000 --- a/dotnet/v3.4/Creatives/CreateImageDisplayCreative.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.IO; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an image display - /// creative associated with a given advertiser. To get a size ID, run - /// GetSize.cs. - /// - class CreateImageDisplayCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an image display" + - " creative associated with a given advertiser. To get a size ID," + - " run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateImageDisplayCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string pathToImageAssetFile = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test image display creative"; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY"; - - // Upload the image asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId imageAssetId = - assetUtils.uploadAsset(pathToImageAssetFile, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset = new CreativeAsset(); - imageAsset.AssetIdentifier = imageAssetId; - imageAsset.Role = "PRIMARY"; - - // Add the creative assets. - creative.CreativeAssets = new List() { imageAsset }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Image display creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateInstreamAudioCreative.cs b/dotnet/v3.4/Creatives/CreateInstreamAudioCreative.cs deleted file mode 100755 index 3b4835f..0000000 --- a/dotnet/v3.4/Creatives/CreateInstreamAudioCreative.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an in-stream audio - /// creative associated with a given advertiser. - /// - class CreateInstreamAudioCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an" + - " in-stream audio creative associated with a given advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateInstreamAudioCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string audioAssetName = _T("INSERT_AUDIO_ASSET_NAME_HERE"); - string pathToAudioAssetFile = _T("INSERT_PATH_TO_AUDIO_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test in-stream audio creative"; - creative.Type = "INSTREAM_AUDIO"; - - // Upload the audio asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId audioAssetId = - assetUtils.uploadAsset(pathToAudioAssetFile, "AUDIO").AssetIdentifier; - - CreativeAsset audioAsset = new CreativeAsset(); - audioAsset.AssetIdentifier = audioAssetId; - audioAsset.Role = "PARENT_AUDIO"; - - // Add the creative assets. - creative.CreativeAssets = new List() { audioAsset }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("In-stream audio creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateInstreamVideoCreative.cs b/dotnet/v3.4/Creatives/CreateInstreamVideoCreative.cs deleted file mode 100755 index fcc0cc1..0000000 --- a/dotnet/v3.4/Creatives/CreateInstreamVideoCreative.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an in-stream video - /// creative associated with a given advertiser. - /// - class CreateInstreamVideoCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an" + - " in-stream video creative associated with a given advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateInstreamVideoCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string videoAssetName = _T("INSERT_VIDEO_ASSET_NAME_HERE"); - string pathToVideoAssetFile = _T("INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test in-stream video creative"; - creative.Type = "INSTREAM_VIDEO"; - - // Upload the video asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId videoAssetId = - assetUtils.uploadAsset(pathToVideoAssetFile, "VIDEO").AssetIdentifier; - - CreativeAsset videoAsset = new CreativeAsset(); - videoAsset.AssetIdentifier = videoAssetId; - videoAsset.Role = "PARENT_VIDEO"; - - // Add the creative assets. - creative.CreativeAssets = new List() { videoAsset }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("In-stream video creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/CreateTrackingCreative.cs b/dotnet/v3.4/Creatives/CreateTrackingCreative.cs deleted file mode 100755 index 65feeef..0000000 --- a/dotnet/v3.4/Creatives/CreateTrackingCreative.cs +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a tracking creative associated with a given - /// advertiser. - /// - class CreateTrackingCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a tracking creative associated with a" + - " given advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateTrackingCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test tracking creative"; - creative.Type = "TRACKING_TEXT"; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Tracking creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Creatives/GetCreativeFieldValues.cs b/dotnet/v3.4/Creatives/GetCreativeFieldValues.cs deleted file mode 100755 index 3a51c31..0000000 --- a/dotnet/v3.4/Creatives/GetCreativeFieldValues.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example retrieves available creative field values for a given string - /// and displays the names and IDs. - /// - class GetCreativeFieldValues : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example retrieves available creative field values for a" + - " given string and displays the names and IDs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreativeFieldValues(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long creativeFieldId = long.Parse(_T("ENTER_CREATIVE_FIELD_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - CreativeFieldValuesListResponse values; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - CreativeFieldValuesResource.ListRequest request = - service.CreativeFieldValues.List(profileId, creativeFieldId); - request.PageToken = nextPageToken; - values = request.Execute(); - - foreach (CreativeFieldValue value in values.CreativeFieldValues) { - Console.WriteLine("Found creative field value with ID {0} and value \"{1}\".", - value.Id, value.Value); - } - - // Update the next page token. - nextPageToken = values.NextPageToken; - } while (values.CreativeFieldValues.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Creatives/GetCreativeFields.cs b/dotnet/v3.4/Creatives/GetCreativeFields.cs deleted file mode 100755 index 4b58dbb..0000000 --- a/dotnet/v3.4/Creatives/GetCreativeFields.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all creative fields. - /// - class GetCreativeFields : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all creative fields.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreativeFields(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - CreativeFieldsListResponse fields; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - CreativeFieldsResource.ListRequest request = service.CreativeFields.List(profileId); - request.PageToken = nextPageToken; - fields = request.Execute(); - - foreach (CreativeField field in fields.CreativeFields) { - Console.WriteLine("Found creative field with ID {0} and name \"{1}\".", - field.Id, field.Name); - } - - // Update the next page token. - nextPageToken = fields.NextPageToken; - } while (fields.CreativeFields.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Creatives/GetCreativeGroups.cs b/dotnet/v3.4/Creatives/GetCreativeGroups.cs deleted file mode 100755 index acc13e4..0000000 --- a/dotnet/v3.4/Creatives/GetCreativeGroups.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all creative groups. - /// - class GetCreativeGroups : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all creative groups.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreativeGroups(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - CreativeGroupsListResponse groups; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - CreativeGroupsResource.ListRequest request = service.CreativeGroups.List(profileId); - request.PageToken = nextPageToken; - groups = request.Execute(); - - foreach (CreativeGroup group in groups.CreativeGroups) { - Console.WriteLine("Found creative group with ID {0} and value \"{1}\".", - group.Id, group.Name); - } - - // Update the next page token. - nextPageToken = groups.NextPageToken; - } while (groups.CreativeGroups.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Creatives/GetCreatives.cs b/dotnet/v3.4/Creatives/GetCreatives.cs deleted file mode 100755 index 41616ad..0000000 --- a/dotnet/v3.4/Creatives/GetCreatives.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all existing active creatives for a given advertiser. - /// To get an advertiser ID, run GetAdvertisers.cs. - /// - class GetCreatives : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all existing active creatives for a given" + - " advertiser. To get an advertiser ID, run GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreatives(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("ENTER_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,creatives(id,name,type)"; - - CreativesListResponse creatives; - String nextPageToken = null; - - do { - // Create and execute the campaigns list request. - CreativesResource.ListRequest request = service.Creatives.List(profileId); - request.Active = true; - request.AdvertiserId = advertiserId; - request.Fields = fields; - request.PageToken = nextPageToken; - creatives = request.Execute(); - - foreach (Creative creative in creatives.Creatives) { - Console.WriteLine("Found {0} creative with ID {1} and name \"{2}\".", - creative.Type, creative.Id, creative.Name); - } - - // Update the next page token. - nextPageToken = creatives.NextPageToken; - } while (creatives.Creatives.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/DfaReporting.Samples.csproj b/dotnet/v3.4/DfaReporting.Samples.csproj deleted file mode 100644 index ce5b0b2..0000000 --- a/dotnet/v3.4/DfaReporting.Samples.csproj +++ /dev/null @@ -1,176 +0,0 @@ - - - - - Debug - AnyCPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC} - Exe - Properties - DfaReporting.Samples - DfaReporting.Samples - v4.5 - 512 - .\ - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - DfaReporting.Samples.Program - - - - packages\Google.Apis.1.48.0\lib\net45\Google.Apis.dll - True - - - packages\Google.Apis.Auth.1.48.0\lib\net45\Google.Apis.Auth.dll - True - - - packages\Google.Apis.Auth.1.48.0\lib\net45\Google.Apis.Auth.PlatformServices.dll - True - - - packages\Google.Apis.Core.1.48.0\lib\net45\Google.Apis.Core.dll - True - - - packages\Google.Apis.Dfareporting.v3_4.1.48.0.2029\lib\net45\Google.Apis.Dfareporting.v3_4.dll - True - - - packages\Google.Apis.1.48.0\lib\net45\Google.Apis.PlatformServices.dll - True - - - packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Always - - - - - - diff --git a/dotnet/v3.4/DfaReporting.Samples.sln b/dotnet/v3.4/DfaReporting.Samples.sln deleted file mode 100755 index cc59936..0000000 --- a/dotnet/v3.4/DfaReporting.Samples.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DfaReporting.Samples", "DfaReporting.Samples.csproj", "{2425B70F-5543-4E51-B8D0-D7A9D04259BC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/dotnet/v3.4/DfaReportingDateConverterUtil.cs b/dotnet/v3.4/DfaReportingDateConverterUtil.cs deleted file mode 100755 index 9377029..0000000 --- a/dotnet/v3.4/DfaReportingDateConverterUtil.cs +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; - -namespace DfaReporting.Samples { - /// - /// This simple utility converts DateTime objects to the string - /// formats that the DCM/DFA Reporting and Trafficking API expects dates to - /// be in. - /// - internal static class DfaReportingDateConverterUtil { - private const string DateFormat = "yyyy-MM-dd"; - private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.FFFZ"; - - /// - /// Takes a DateTime object and converts it to the proper date-only - /// string format for the DCM/DFA Reporting and Trafficking API. - /// - /// The date to be converted. - /// The given date in the proper format. - public static string convertToDateString(DateTime date) { - return date.ToString(DateFormat); - } - - /// - /// Takes a DateTime object and converts it to the proper datetime - /// string format for the DCM/DFA Reporting and Trafficking API. - /// - /// The date to be converted. - /// The given date in the proper format. - public static string convertToDateTimeString(DateTime date) { - return date.ToString(DateTimeFormat); - } - } -} \ No newline at end of file diff --git a/dotnet/v3.4/DfaReportingFactory.cs b/dotnet/v3.4/DfaReportingFactory.cs deleted file mode 100755 index f168665..0000000 --- a/dotnet/v3.4/DfaReportingFactory.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Threading; -using Google.Apis.Auth.OAuth2; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Services; -using Google.Apis.Util.Store; - -namespace DfaReporting.Samples { - /// - /// Factory for generating DFA Reporting and Trafficking API service objects. - /// - class DfaReportingFactory { - /// - /// The scopes used to make reporting and trafficking requests. - /// - private static readonly IEnumerable scopes = new[] { - DfareportingService.Scope.Dfareporting, - DfareportingService.Scope.Dfatrafficking, - DfareportingService.Scope.Ddmconversions - }; - - /// - /// Authorizes the application to access users' protected data. - /// - private static ICredential Authorize() { - // Load application default credentials if they're available. - ICredential credential = LoadApplicationDefaultCredentials(); - - // Otherwise, load credentials from the provided client secrets file. - if (credential == null) { - credential = LoadUserCredentials("client_secrets.json", - new FileDataStore("DfaReporting.Samples")); - } - - return credential; - } - - /// - /// Attempts to load the application default credentials - /// - /// The application default credentials, or null if none were found. - private static ICredential LoadApplicationDefaultCredentials() { - try { - GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result; - return credential.CreateScoped(scopes); - } catch (Exception) { - // No application default credentials, continue to try other options. - } - - return null; - } - - /// - /// Attempts to load user credentials from the provided client secrets file and persists data to - /// the provided data store. - /// - /// The user credentials. - /// Path to the file containing client secrets. - /// The data store to use for caching credential information. - private static ICredential LoadUserCredentials(String clientSecretsFile, IDataStore dataStore) { - using (var stream = new System.IO.FileStream(clientSecretsFile, System.IO.FileMode.Open, - System.IO.FileAccess.Read)) { - return GoogleWebAuthorizationBroker.AuthorizeAsync( - GoogleClientSecrets.Load(stream).Secrets, - scopes, - "dfa-user", CancellationToken.None, - dataStore).Result; - } - } - - /// - /// Initializes a DfaReportingService instance. - /// - /// An initialized DfaReportingService object. - public static DfareportingService getInstance() { - ICredential credential = Authorize(); - - // Create and return the service. - return new DfareportingService(new BaseClientService.Initializer { - HttpClientInitializer = credential, - ApplicationName = "DFA/DCM Reporting and Trafficking API Samples" - }); - } - } -} diff --git a/dotnet/v3.4/Floodlight/CreateFloodlightActivity.cs b/dotnet/v3.4/Floodlight/CreateFloodlightActivity.cs deleted file mode 100755 index a81af5d..0000000 --- a/dotnet/v3.4/Floodlight/CreateFloodlightActivity.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a floodlight activity in a given activity group. To - /// create an activity group, run CreateFloodlightActivityGroup.cs. - /// - class CreateFloodlightActivity : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a floodlight activity in a given" + - " activity group. To create an activity group, run" + - " CreateFloodlightActivityGroup.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateFloodlightActivity(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long activityGroupId = long.Parse(_T("INSERT_ACTIVITY_GROUP_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String activityName = _T("INSERT_ACTIVITY_NAME_HERE"); - String url = _T("INSERT_EXPECTED_URL_HERE"); - - // Set floodlight activity structure. - FloodlightActivity activity = new FloodlightActivity(); - activity.CountingMethod = "STANDARD_COUNTING"; - activity.Name = activityName; - activity.FloodlightActivityGroupId = activityGroupId; - activity.FloodlightTagType = "GLOBAL_SITE_TAG"; - activity.ExpectedUrl = url; - - // Create the floodlight tag activity. - FloodlightActivity result = - service.FloodlightActivities.Insert(activity, profileId).Execute(); - - // Display new floodlight activity ID. - if (result != null) { - Console.WriteLine("Floodlight activity with ID {0} was created.", result.Id); - } - } - } -} diff --git a/dotnet/v3.4/Floodlight/CreateFloodlightActivityGroup.cs b/dotnet/v3.4/Floodlight/CreateFloodlightActivityGroup.cs deleted file mode 100755 index 83888a8..0000000 --- a/dotnet/v3.4/Floodlight/CreateFloodlightActivityGroup.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a new activity group for a given floodlight - /// configuration. To get a floodlight tag configuration ID, run - /// GetAdvertisers.cs. - /// - class CreateFloodlightActivityGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a new activity group for a given" + - " floodlight configuration. To get a floodlight tag configuration" + - " ID, run GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateFloodlightActivityGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long floodlightConfigurationId = - long.Parse(_T("INSERT_FLOODLIGHT_CONFIGURATION_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String groupName = _T("INSERT_GROUP_NAME_HERE"); - - // Create the floodlight activity group. - FloodlightActivityGroup floodlightActivityGroup = new FloodlightActivityGroup(); - floodlightActivityGroup.Name = groupName; - floodlightActivityGroup.FloodlightConfigurationId = floodlightConfigurationId; - floodlightActivityGroup.Type = "COUNTER"; - - // Insert the activity group. - FloodlightActivityGroup result = - service.FloodlightActivityGroups.Insert(floodlightActivityGroup, profileId).Execute(); - - // Display the new activity group ID. - if (result != null) { - Console.WriteLine("Activity group with ID {0} was created.", result.Id); - } - } - } -} diff --git a/dotnet/v3.4/Floodlight/DownloadFloodlightTags.cs b/dotnet/v3.4/Floodlight/DownloadFloodlightTags.cs deleted file mode 100755 index 49d003c..0000000 --- a/dotnet/v3.4/Floodlight/DownloadFloodlightTags.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example downloads activity tags for a given floodlight activity. - /// - class DownloadFloodlightTags : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example downloads activity tags for a given floodlight" + - " activity.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DownloadFloodlightTags(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long activityId = long.Parse(_T("ENTER_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Generate the floodlight activity tag. - FloodlightActivitiesResource.GeneratetagRequest request = - service.FloodlightActivities.Generatetag(profileId); - request.FloodlightActivityId = activityId; - - FloodlightActivitiesGenerateTagResponse response = request.Execute(); - - if (response.GlobalSiteTagGlobalSnippet != null) { - // This is a global site tag, display both the global snippet and event snippet. - Console.WriteLine("Global site tag global snippet:\n\n{0}", - response.GlobalSiteTagGlobalSnippet); - Console.WriteLine("\n\nGlobal site tag event snippet:\n\n{0}", - response.FloodlightActivityTag); - } else { - // This is an image or iframe tag. - Console.WriteLine("Floodlight activity tag:\n\n{0}", response.FloodlightActivityTag); - } - } - } -} diff --git a/dotnet/v3.4/Floodlight/GetFloodlightActivities.cs b/dotnet/v3.4/Floodlight/GetFloodlightActivities.cs deleted file mode 100755 index 7c88af1..0000000 --- a/dotnet/v3.4/Floodlight/GetFloodlightActivities.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays floodlight activities for a given advertiser. To - /// create an advertiser, run CreateAdvertiser.cs. - /// - class GetFloodlightActivities : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays floodlight activities for a given" + - " advertiser. To create an advertiser, run CreateAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetFloodlightActivities(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,floodlightActivities(id,name)"; - - FloodlightActivitiesListResponse activities; - String nextPageToken = null; - - do { - // Create and execute the floodlight activities list request. - FloodlightActivitiesResource.ListRequest request = - service.FloodlightActivities.List(profileId); - request.AdvertiserId = advertiserId; - request.Fields = fields; - request.PageToken = nextPageToken; - activities = request.Execute(); - - foreach (FloodlightActivity activity in activities.FloodlightActivities) { - Console.WriteLine("Floodlight activity with ID {0} and name \"{1}\"" + - " was found.", activity.Id, activity.Name); - } - - // Update the next page token. - nextPageToken = activities.NextPageToken; - } while (activities.FloodlightActivities.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Floodlight/GetFloodlightActivityGroups.cs b/dotnet/v3.4/Floodlight/GetFloodlightActivityGroups.cs deleted file mode 100755 index 00238fd..0000000 --- a/dotnet/v3.4/Floodlight/GetFloodlightActivityGroups.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays floodlight activity groups for a given advertiser. - /// To create an advertiser, run CreateAdvertiser.cs. - /// - class GetFloodlightActivityGroups : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays floodlight activity groups for a given" + - " advertiser. To create an advertiser, run CreateAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetFloodlightActivityGroups(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "floodlightActivityGroups(id,name)"; - - // Create and execute the floodlight activity groups list request. - FloodlightActivityGroupsResource.ListRequest request = - service.FloodlightActivityGroups.List(profileId); - request.AdvertiserId = advertiserId; - request.Fields = fields; - FloodlightActivityGroupsListResponse groups = request.Execute(); - - foreach (FloodlightActivityGroup group in groups.FloodlightActivityGroups) { - Console.WriteLine("Floodlight activity group with ID {0} and name" + - " \"{1}\" was found.", group.Id, group.Name); - } - } - } -} diff --git a/dotnet/v3.4/Misc/GetChangeLogsForAdvertiser.cs b/dotnet/v3.4/Misc/GetChangeLogsForAdvertiser.cs deleted file mode 100755 index 4f65160..0000000 --- a/dotnet/v3.4/Misc/GetChangeLogsForAdvertiser.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the change logs of a specified advertiser object. - /// A similar pattern can be applied to get change logs for many other object - /// types. - /// - class GetChangeLogsForAdvertiser : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the change logs of a specified" + - " advertiser object. A similar pattern can be applied to get" + - " change logs for many other object types.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetChangeLogsForAdvertiser(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,changeLogs(action,fieldName,oldValue,newValue)"; - - ChangeLogsListResponse changeLogs; - String nextPageToken = null; - - do { - // Create and execute the change logs list request - ChangeLogsResource.ListRequest request = service.ChangeLogs.List(profileId); - request.ObjectIds = advertiserId.ToString(); - request.ObjectType = ChangeLogsResource.ListRequest.ObjectTypeEnum.OBJECTADVERTISER; - request.Fields = fields; - request.PageToken = nextPageToken; - changeLogs = request.Execute(); - - foreach (ChangeLog changeLog in changeLogs.ChangeLogs) { - Console.WriteLine("{0}: Field \"{1}\" from \"{2}\" to \"{3}\".", - changeLog.Action, changeLog.FieldName, changeLog.OldValue, - changeLog.NewValue); - } - - // Update the next page token. - nextPageToken = changeLogs.NextPageToken; - } while (changeLogs.ChangeLogs.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Misc/GetSites.cs b/dotnet/v3.4/Misc/GetSites.cs deleted file mode 100755 index d510bd3..0000000 --- a/dotnet/v3.4/Misc/GetSites.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all existing sites. - /// - class GetSites : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all existing sites.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSites(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,sites(id,keyName)"; - - SitesListResponse sites; - String nextPageToken = null; - - do { - // Create and execute the sites list request. - SitesResource.ListRequest request = service.Sites.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - sites = request.Execute(); - - foreach (Site site in sites.Sites) { - Console.WriteLine("Found site with ID {0} and key name \"{1}\".", - site.Id, site.KeyName); - } - - // Update the next page token. - nextPageToken = sites.NextPageToken; - } while (sites.Sites.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Misc/GetSize.cs b/dotnet/v3.4/Misc/GetSize.cs deleted file mode 100755 index 5c2f5f2..0000000 --- a/dotnet/v3.4/Misc/GetSize.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all sizes for a given width and height. - /// - class GetSize : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all sizes for a given width and height.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSize(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - int height = int.Parse(_T("ENTER_HEIGHT_HERE")); - int width = int.Parse(_T("ENTER_WIDTH_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Create and execute the sizes list request. - SizesResource.ListRequest request = service.Sizes.List(profileId); - request.Height = height; - request.Width = width; - SizesListResponse sizes = request.Execute(); - - foreach (Size size in sizes.Sizes) { - Console.WriteLine("Found size with ID {0}.", size.Id); - } - } - } -} diff --git a/dotnet/v3.4/Placements/CreateContentCategory.cs b/dotnet/v3.4/Placements/CreateContentCategory.cs deleted file mode 100755 index ecd43e3..0000000 --- a/dotnet/v3.4/Placements/CreateContentCategory.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a content category with the given name and - /// description. - /// - class CreateContentCategory : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a content category with the given name" + - " and description.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateContentCategory(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String contentCategoryName = _T("INSERT_CONTENT_CATEGORY_NAME_HERE"); - - // Create the content category. - ContentCategory contentCategory = new ContentCategory(); - contentCategory.Name = contentCategoryName; - - // Insert the content category. - ContentCategory result = - service.ContentCategories.Insert(contentCategory, profileId).Execute(); - - // Display the new content category ID. - Console.WriteLine("Content category with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Placements/CreatePlacement.cs b/dotnet/v3.4/Placements/CreatePlacement.cs deleted file mode 100755 index baf93b5..0000000 --- a/dotnet/v3.4/Placements/CreatePlacement.cs +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a placement in a given campaign. Requires a DFA site - /// ID and ID of the campaign in which the placement will be created. To - /// create a campaign, run CreateCampaign.cs. To get a DFA site ID, run - /// GetSite.cs. To get a size ID, run GetSize.cs. - /// - class CreatePlacement : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a placement in a given campaign." + - " Requires a DFA site ID and ID of the campaign in which the" + - " placement will be created. To create a campaign, run" + - " CreateCampaign.cs. To get a DFA site ID, run GetSite.cs. To get" + - " a size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreatePlacement(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long dfaSiteId = long.Parse(_T("INSERT_SITE_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string placementName = _T("INSERT_PLACEMENT_NAME_HERE"); - - // Retrieve the campaign. - Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute(); - - // Create the placement. - Placement placement = new Placement(); - placement.Name = placementName; - placement.CampaignId = campaignId; - placement.Compatibility = "DISPLAY"; - placement.PaymentSource = "PLACEMENT_AGENCY_PAID"; - placement.SiteId = dfaSiteId; - placement.TagFormats = new List() { "PLACEMENT_TAG_STANDARD" }; - - // Set the size of the placement. - Size size = new Size(); - size.Id = sizeId; - placement.Size = size; - - // Set the pricing schedule for the placement. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.EndDate = campaign.EndDate; - pricingSchedule.PricingType = "PRICING_TYPE_CPM"; - pricingSchedule.StartDate = campaign.StartDate; - placement.PricingSchedule = pricingSchedule; - - // Insert the placement. - Placement result = service.Placements.Insert(placement, profileId).Execute(); - - // Display the new placement ID. - Console.WriteLine("Placement with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Placements/CreatePlacementGroup.cs b/dotnet/v3.4/Placements/CreatePlacementGroup.cs deleted file mode 100755 index ee55dfa..0000000 --- a/dotnet/v3.4/Placements/CreatePlacementGroup.cs +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a placement group in a given campaign. Requires the - /// DFA site ID and campaign ID in which the placement group will be created - /// into. To create a campaign, run CreateCampaign.cs. To get DFA site ID, - /// run GetSite.cs. - /// - class CreatePlacementGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a placement group in a given campaign." + - " Requires the DFA site ID and campaign ID in which the placement" + - " group will be created into. To create a campaign, run" + - " CreateCampaign.cs. To get DFA site ID, run GetSite.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreatePlacementGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long dfaSiteId = long.Parse(_T("INSERT_SITE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string placementGroupName = _T("INSERT_PLACEMENT_GROUP_NAME_HERE"); - - // Retrieve the campaign. - Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute(); - - // Create a pricing schedule. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.EndDate = campaign.EndDate; - pricingSchedule.PricingType = "PRICING_TYPE_CPM"; - pricingSchedule.StartDate = campaign.StartDate; - - // Create the placement group. - PlacementGroup placementGroup = new PlacementGroup(); - placementGroup.CampaignId = campaignId; - placementGroup.Name = placementGroupName; - placementGroup.PlacementGroupType = "PLACEMENT_PACKAGE"; - placementGroup.PricingSchedule = pricingSchedule; - placementGroup.SiteId = dfaSiteId; - - // Insert the placement. - PlacementGroup result = - service.PlacementGroups.Insert(placementGroup, profileId).Execute(); - - // Display the new placement ID. - Console.WriteLine("Placement group with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Placements/CreatePlacementStrategy.cs b/dotnet/v3.4/Placements/CreatePlacementStrategy.cs deleted file mode 100755 index 89f7c07..0000000 --- a/dotnet/v3.4/Placements/CreatePlacementStrategy.cs +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a placement strategy with the given name. - /// - class CreatePlacementStrategy : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a placement strategy with the given name.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreatePlacementStrategy(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string placementStrategyName = _T("INSERT_PLACEMENT_STRATEGY_NAME_HERE"); - - // Create the placement strategy. - PlacementStrategy placementStrategy = new PlacementStrategy(); - placementStrategy.Name = placementStrategyName; - - // Insert the placement strategy. - PlacementStrategy result = - service.PlacementStrategies.Insert(placementStrategy, profileId).Execute(); - - // Display the new placement strategy ID. - Console.WriteLine("Placement strategy with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Placements/DownloadPlacementTags.cs b/dotnet/v3.4/Placements/DownloadPlacementTags.cs deleted file mode 100755 index cbe0a76..0000000 --- a/dotnet/v3.4/Placements/DownloadPlacementTags.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example downloads HTML Tags for a given campaign and placement ID. - /// To create campaigns, run CreateCampaign.cs. To create placements, run - /// CreatePlacement.cs. - /// - class DownloadPlacementTags : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example downloads HTML Tags for a given campaign and" + - " placement ID. To create campaigns, run CreateCampaign.cs. To" + - " create placements, run CreatePlacement.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DownloadPlacementTags(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("ENTER_CAMPAIGN_ID_HERE")); - long placementId = long.Parse(_T("ENTER_PLACEMENT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Generate the placement activity tags. - PlacementsResource.GeneratetagsRequest request = - service.Placements.Generatetags(profileId); - request.CampaignId = campaignId; - request.TagFormats = - PlacementsResource.GeneratetagsRequest.TagFormatsEnum.PLACEMENTTAGIFRAMEJAVASCRIPT; - request.PlacementIds = placementId.ToString(); - - PlacementsGenerateTagsResponse response = request.Execute(); - - // Display the placement activity tags. - foreach (PlacementTag tag in response.PlacementTags) { - foreach (TagData tagData in tag.TagDatas) { - Console.WriteLine("{0}:\n", tagData.Format); - - if (tagData.ImpressionTag != null) { - Console.WriteLine(tagData.ImpressionTag); - } - - if (tagData.ClickTag != null) { - Console.WriteLine(tagData.ClickTag); - } - - Console.WriteLine(); - } - } - } - } -} diff --git a/dotnet/v3.4/Placements/GetContentCategories.cs b/dotnet/v3.4/Placements/GetContentCategories.cs deleted file mode 100755 index a267468..0000000 --- a/dotnet/v3.4/Placements/GetContentCategories.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all available content categories. - /// - class GetContentCategories : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all available content categories.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetContentCategories(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,contentCategories(id,name)"; - - ContentCategoriesListResponse categories; - String nextPageToken = null; - - do { - // Create and execute the content categories list request - ContentCategoriesResource.ListRequest request = - service.ContentCategories.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - categories = request.Execute(); - - foreach (ContentCategory category in categories.ContentCategories) { - Console.WriteLine("Found content category with ID {0} and name \"{1}\".", - category.Id, category.Name); - } - - // Update the next page token - nextPageToken = categories.NextPageToken; - } while (categories.ContentCategories.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Placements/GetPlacementStrategies.cs b/dotnet/v3.4/Placements/GetPlacementStrategies.cs deleted file mode 100755 index 25eb316..0000000 --- a/dotnet/v3.4/Placements/GetPlacementStrategies.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all available placement strategies. - /// - class GetPlacementStrategies : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all available placement strategies.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetPlacementStrategies(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,placementStrategies(id,name)"; - - PlacementStrategiesListResponse strategies; - String nextPageToken = null; - - do { - // Create and execute the placement strategies list request - PlacementStrategiesResource.ListRequest request = - service.PlacementStrategies.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - strategies = request.Execute(); - - foreach (PlacementStrategy strategy in strategies.PlacementStrategies) { - Console.WriteLine("Found placement strategy with ID {0} and name \"{1}\".", - strategy.Id, strategy.Name); - } - - // Update the next page token - nextPageToken = strategies.NextPageToken; - } while (strategies.PlacementStrategies.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Placements/GetPlacements.cs b/dotnet/v3.4/Placements/GetPlacements.cs deleted file mode 100755 index 6ed98b5..0000000 --- a/dotnet/v3.4/Placements/GetPlacements.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all available placement strategies. - /// - class GetPlacements : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all available placement strategies.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetPlacements(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,placements(campaignId,id,name)"; - - PlacementsListResponse placements; - String nextPageToken = null; - - do { - // Create and execute the placements list request - PlacementsResource.ListRequest request = service.Placements.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - placements = request.Execute(); - - foreach (Placement placement in placements.Placements) { - Console.WriteLine( - "Placement with ID {0} and name \"{1}\" is associated with campaign ID {2}.", - placement.Id, placement.Name, placement.CampaignId); - } - - // Update the next page token - nextPageToken = placements.NextPageToken; - } while (placements.Placements.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Program.cs b/dotnet/v3.4/Program.cs deleted file mode 100755 index a987058..0000000 --- a/dotnet/v3.4/Program.cs +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using Google.Apis.Dfareporting.v3_4; - -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; - -using SamplePair = System.Collections.Generic.KeyValuePair; - -namespace DfaReporting.Samples { - /// - /// The Main class for this application. - /// - class Program { - /// - /// A map to hold the code examples to be executed. - /// - static List sampleMap = new List(); - - /// - /// A flag to keep track of whether help message was shown earlier. - /// - private static bool helpShown = false; - - static void RegisterSample(string key, SampleBase value) { - sampleMap.Add(new SamplePair(key, value)); - } - /// - /// Static constructor to initialize the sample map. - /// - static Program() { - Type[] types = Assembly.GetExecutingAssembly().GetTypes(); - - foreach (Type type in types) { - if (type.BaseType == typeof(SampleBase)) { - RegisterSample(type.FullName.Replace(typeof(Program).Namespace + ".", ""), - Activator.CreateInstance(type) as SampleBase); - } - } - } - - /// - /// The main method. - /// - /// - public static void Main(string[] args) { - if (args.Length == 0) { - ShowUsage(); - return; - } - - foreach (string cmdArgs in args) { - SamplePair matchingPair = sampleMap.Find(delegate(SamplePair pair) { - return string.Compare(pair.Key, cmdArgs, true) == 0; - }); - - if (matchingPair.Key != null) { - // Initialize the Dfa Reporting service. - DfareportingService service = DfaReportingFactory.getInstance(); - - // Run the sample - RunASample(service, matchingPair.Value); - } else { - ShowUsage(); - } - } - } - - /// - /// Runs a code sample. - /// - /// The user whose credentials should be used for - /// running the sample. - /// The code sample to run. - private static void RunASample(DfareportingService service, SampleBase sample) { - try { - Console.WriteLine(sample.Description); - sample.Run(service); - } catch (Exception ex) { - Console.WriteLine("An exception occurred while running this code example.\n{0} at\n{1}", - ex.Message, ex.StackTrace); - } finally { - Console.WriteLine("Press [Enter] to continue"); - Console.ReadLine(); - } - } - - /// - /// Prints program usage message. - /// - private static void ShowUsage() { - if (helpShown) { - return; - } else { - helpShown = true; - } - string exeName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); - Console.WriteLine("Runs DFA/DCM Reporting and Trafficking API code examples"); - Console.WriteLine("Usage : {0} [flags]\n", exeName); - Console.WriteLine("Available flags\n"); - Console.WriteLine("--help\t\t : Prints this help message."); - Console.WriteLine("examplename1 [examplename1 ...] : " + - "Run specific code examples. Example name can be one of the following:\n"); - foreach (SamplePair pair in sampleMap) { - Console.WriteLine("{0} : {1}", pair.Key, pair.Value.Description); - } - Console.WriteLine("Press [Enter] to continue"); - Console.ReadLine(); - } - } -} diff --git a/dotnet/v3.4/Properties/AssemblyInfo.cs b/dotnet/v3.4/Properties/AssemblyInfo.cs deleted file mode 100755 index 34bdabb..0000000 --- a/dotnet/v3.4/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("DfaReporting.Samples")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("DfaReporting.Samples")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e98d0eed-6c41-44d3-9739-bd2cee72f51b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet/v3.4/README.md b/dotnet/v3.4/README.md deleted file mode 100644 index ab05011..0000000 --- a/dotnet/v3.4/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# DCM/DFA Reporting and Trafficking API .NET Samples - -This is a collection of samples written in C# which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - -Install Visual Studio 2013+ and Nuget 2.12+ - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Running the Examples - -Once you've checked out the code: - -1. Open the DfaReporting.Samples.csproj file. - -2. Choose a sample and fill in any prerequisite values. Required values can be identified by the placeholder text: "ENTER_..._HERE". - -3. Add the sample name as a command line argument and build/run the project. - -4. Complete the authorization steps on your browser. - -5. Examine the console output, be inspired and start hacking an amazing new app! diff --git a/dotnet/v3.4/Remarketing/CreateRemarketingList.cs b/dotnet/v3.4/Remarketing/CreateRemarketingList.cs deleted file mode 100755 index 6fd91ec..0000000 --- a/dotnet/v3.4/Remarketing/CreateRemarketingList.cs +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a remarketing list for a given advertiser and floodlight activity, using - /// a custom rule. - /// - /// Note: this sample assumes that the floodlight activity specified has a U1 custom floodlight - /// variable. - /// - class CreateRemarketingList : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a remarketing list for a given advertiser" + - " and floodlight activity, using a custom rule.\n\n" + - "Note: this sample assumes that the floodlight activity specified" + - " has a U1 custom floodlight variable.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateRemarketingList(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string remarketingListName = _T("INSERT_REMARKETING_LIST_NAME_HERE"); - - // Create the remarketing list. - RemarketingList remarketingList = new RemarketingList(); - remarketingList.Active = true; - remarketingList.AdvertiserId = advertiserId; - remarketingList.LifeSpan = 30L; - remarketingList.Name = remarketingListName; - - // Create a list population term. - // This term matches all visitors with a U1 value exactly matching "test_value". - ListPopulationTerm term = new ListPopulationTerm(); - term.Operator__ = "STRING_EQUALS"; - term.Type = "CUSTOM_VARIABLE_TERM"; - term.Value = "test_value"; - term.VariableName = "U1"; - - // Add the term to a list population clause. - ListPopulationClause clause = new ListPopulationClause(); - clause.Terms = new List { term }; - - // Add the clause to a list population rule. - // This rule will target all visitors who trigger the specified floodlight activity and - // satisfy the custom rule defined in the list population term. - ListPopulationRule rule = new ListPopulationRule(); - rule.FloodlightActivityId = floodlightActivityId; - rule.ListPopulationClauses = new List { clause }; - remarketingList.ListPopulationRule = rule; - - // Insert the remarketing list. - RemarketingList result = - service.RemarketingLists.Insert(remarketingList, profileId).Execute(); - - // Display the new remarketing list ID. - Console.WriteLine("Remarketing list with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Remarketing/GetRemarketingLists.cs b/dotnet/v3.4/Remarketing/GetRemarketingLists.cs deleted file mode 100755 index 2507532..0000000 --- a/dotnet/v3.4/Remarketing/GetRemarketingLists.cs +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all remarketing lists owned by the specified advertiser. - /// - /// Note: the RemarketingLists resource will only return lists owned by the specified advertiser. - /// To see all lists that can be used for targeting ads (including those shared from other - /// accounts or advertisers), use the TargetableRemarketingLists resource instead. - /// - class GetRemarketingLists : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all remarketing lists owned by the specified advertiser." + - "\n\nNote: the RemarketingLists resource will only return lists owned by the" + - " specified advertiser. To see all lists that can be used for targeting ads" + - " including those shared from other accounts or advertisers), use the" + - " TargetableRemarketingLists resource instead.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetRemarketingLists(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,remarketingLists(accountId,advertiserId,id,name)"; - - RemarketingListsListResponse lists; - String nextPageToken = null; - - do { - // Create and execute the remaketing lists list request - RemarketingListsResource.ListRequest request = - service.RemarketingLists.List(profileId, advertiserId); - request.Fields = fields; - request.PageToken = nextPageToken; - lists = request.Execute(); - - foreach (RemarketingList list in lists.RemarketingLists) { - Console.WriteLine( - "Remarketing list with ID {0} and name \"{1}\" was found.", - list.Id, list.Name); - } - - // Update the next page token - nextPageToken = lists.NextPageToken; - } while (lists.RemarketingLists.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Remarketing/ShareRemarketingListToAdvertiser.cs b/dotnet/v3.4/Remarketing/ShareRemarketingListToAdvertiser.cs deleted file mode 100755 index 2a33de5..0000000 --- a/dotnet/v3.4/Remarketing/ShareRemarketingListToAdvertiser.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example shares an existing remarketing list with the specified advertiser. - /// - class ShareRemarketingListToAdvertiser : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example shares an existing remarketing list with the specified" + - " advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new ShareRemarketingListToAdvertiser(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long remarketingListId = long.Parse(_T("INSERT_REMARKETING_LIST_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Load the existing share info. - RemarketingListShare share = - service.RemarketingListShares.Get(profileId, remarketingListId).Execute(); - - if(share.SharedAdvertiserIds == null) { - share.SharedAdvertiserIds = new List {}; - } - - if(!share.SharedAdvertiserIds.Contains(advertiserId)) { - share.SharedAdvertiserIds.Add(advertiserId); - - // Update the share info with the newly added advertiser ID. - RemarketingListShare result = - service.RemarketingListShares.Update(share, profileId).Execute(); - - Console.WriteLine( - "Remarketing list with ID {0} is now shared to advertiser ID(s): {1}.\n", - result.RemarketingListId, string.Join(", ", result.SharedAdvertiserIds)); - } else { - Console.WriteLine( - "Remarketing list with ID {0} is already shared to advertiser ID {1}.\n", - remarketingListId, advertiserId); - } - } - } -} diff --git a/dotnet/v3.4/Remarketing/TargetAdToRemarketingList.cs b/dotnet/v3.4/Remarketing/TargetAdToRemarketingList.cs deleted file mode 100755 index de95412..0000000 --- a/dotnet/v3.4/Remarketing/TargetAdToRemarketingList.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example targets an ad to a remarketing list. - /// - /// The first targetable remarketing list, either owned by or shared to the ad's advertiser, - /// will be used. To create a remarketing list, see CreateRemarketingList.cs. To share a - /// remarketing list with the ad's advertiser, see ShareRemarketingListToAdvertiser.cs. - /// - class TargetAdToRemarketingList : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example targets an ad to a remarketing list.\n\nThe first targetable" + - " remarketing list, either owned by or shared to the ad's advertiser, will be used." + - " To create a remarketing list, see CreateRemarketingList.cs. To share a remarketing" + - " list with the ad's advertiser, see ShareRemarketingListToAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new TargetAdToRemarketingList(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long adId = long.Parse(_T("INSERT_AD_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - Ad ad = service.Ads.Get(profileId, adId).Execute(); - - TargetableRemarketingListsResource.ListRequest listRequest = - service.TargetableRemarketingLists.List(profileId, ad.AdvertiserId.Value); - listRequest.MaxResults = 1; - TargetableRemarketingListsListResponse lists = listRequest.Execute(); - - if(lists.TargetableRemarketingLists.Any()) { - // Select the first targetable remarketing list that was returned. - TargetableRemarketingList list = lists.TargetableRemarketingLists.First(); - - // Create a list targeting expression. - ListTargetingExpression expression = new ListTargetingExpression(); - expression.Expression = list.Id.ToString(); - - // Update the ad. - ad.RemarketingListExpression = expression; - Ad result = service.Ads.Update(ad, profileId).Execute(); - - Console.WriteLine( - "Ad with ID {0} updated to use remarketing list expression: {1}.\n", - result.Id, result.RemarketingListExpression.Expression); - } else { - Console.WriteLine("No targetable remarketing lists found for ad with ID {0}.\n", adId); - } - } - } -} diff --git a/dotnet/v3.4/Reports/CreateReport.cs b/dotnet/v3.4/Reports/CreateReport.cs deleted file mode 100755 index 32012f1..0000000 --- a/dotnet/v3.4/Reports/CreateReport.cs +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; -using Newtonsoft.Json; - -namespace DfaReporting.Samples { - /// - /// This example provides an end-to-end example of how to create and - /// configure a standard report. - /// - class CreateReport : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example provides an end-to-end example of how to create " + - "and configure a standard report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // 1. Create a report resource. - Report report = CreateReportResource(); - - // 2. Define the report criteria. - DefineReportCriteria(report); - - // 3. (optional) Look up compatible fields. - FindCompatibleFields(service, profileId, report); - - // 4. Add dimension filters to the report criteria. - AddDimensionFilters(service, profileId, report); - - // 5. Save the report resource. - InsertReportResource(service, profileId, report); - } - - private Report CreateReportResource() { - Report report = new Report(); - - // Set the required fields "name" and "type". - report.Name = "Example standard report"; - report.Type = "STANDARD"; - - // Set optional fields. - report.FileName = "example_report"; - report.Format = "CSV"; - - Console.WriteLine("Creating {0} report resource with name \"{1}\".", - report.Type, report.Name); - - return report; - } - - private void DefineReportCriteria(Report report) { - // Define a date range to report on. This example uses explicit start and - // end dates to mimic the "LAST_30_DAYS" relative date range. - DateRange dateRange = new DateRange(); - dateRange.EndDate = DateTime.Now.ToString("yyyy-MM-dd"); - dateRange.StartDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"); - - // Create a report criteria. - SortedDimension dimension = new SortedDimension(); - dimension.Name = "advertiser"; - - Report.CriteriaData criteria = new Report.CriteriaData(); - criteria.DateRange = dateRange; - criteria.Dimensions = new List() { dimension }; - criteria.MetricNames = new List() { - "clicks", - "impressions" - }; - - // Add the criteria to the report resource. - report.Criteria = criteria; - - Console.WriteLine("\nAdded report criteria:\n{0}", - JsonConvert.SerializeObject(criteria)); - } - - private void FindCompatibleFields(DfareportingService service, - long profileId, Report report) { - CompatibleFields fields = - service.Reports.CompatibleFields.Query(report, profileId).Execute(); - - ReportCompatibleFields reportFields = fields.ReportCompatibleFields; - - if(reportFields.Dimensions.Any()) { - // Add a compatible dimension to the report. - Dimension dimension = reportFields.Dimensions[0]; - SortedDimension sortedDimension = new SortedDimension(); - sortedDimension.Name = dimension.Name; - report.Criteria.Dimensions.Add(sortedDimension); - } else if (reportFields.Metrics.Any()) { - // Add a compatible metric to the report. - Metric metric = reportFields.Metrics[0]; - report.Criteria.MetricNames.Add(metric.Name); - } - - Console.WriteLine( - "\nUpdated report criteria (with compatible fields):\n{0}", - JsonConvert.SerializeObject(report.Criteria)); - } - - private void AddDimensionFilters(DfareportingService service, - long profileId, Report report) { - // Query advertiser dimension values for report run dates. - DimensionValueRequest request = new DimensionValueRequest(); - request.StartDate = report.Criteria.DateRange.StartDate; - request.EndDate = report.Criteria.DateRange.EndDate; - request.DimensionName = "advertiser"; - - DimensionValueList values = - service.DimensionValues.Query(request, profileId).Execute(); - - if (values.Items.Any()) { - // Add a value as a filter to the report criteria. - report.Criteria.DimensionFilters = new List() { - values.Items[0] - }; - } - - Console.WriteLine( - "\nUpdated report criteria (with valid dimension filters):\n{0}", - JsonConvert.SerializeObject(report.Criteria)); - } - - private void InsertReportResource(DfareportingService service, - long profileId, Report report) { - Report insertedReport = - service.Reports.Insert(report, profileId).Execute(); - - Console.WriteLine("\nSuccessfully inserted new report with ID {0}.", - insertedReport.Id); - } - } -} diff --git a/dotnet/v3.4/Reports/DeleteReport.cs b/dotnet/v3.4/Reports/DeleteReport.cs deleted file mode 100755 index db1b15d..0000000 --- a/dotnet/v3.4/Reports/DeleteReport.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to delete a report. - /// - class DeleteReport : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to delete a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DeleteReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("ENTER_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Delete the report. - service.Reports.Delete(profileId, reportId).Execute(); - - // Display the new report ID. - Console.WriteLine("Report with ID {0} was successfully deleted.", reportId); - } - } -} diff --git a/dotnet/v3.4/Reports/DownloadFile.cs b/dotnet/v3.4/Reports/DownloadFile.cs deleted file mode 100755 index 491aa66..0000000 --- a/dotnet/v3.4/Reports/DownloadFile.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Text; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; -using Google.Apis.Download; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to download a file. - /// - class DownloadFile : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to download a file.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DownloadFile(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long fileId = long.Parse(_T("INSERT_FILE_ID_HERE")); - long reportId = long.Parse(_T("ENTER_REPORT_ID_HERE")); - - // Retrive the file metadata. - File file = service.Files.Get(reportId, fileId).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - // Create a get request. - FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize; - - // Execute the get request and download the file. - using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file), - System.IO.FileMode.Create, System.IO.FileAccess.Write)) { - getRequest.Download(outFile); - Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name); - } - } - } - - private string GenerateFileName(File file) { - // If no filename is specified, use the file ID instead. - string fileName = file.FileName; - if (String.IsNullOrEmpty(fileName)) { - fileName = file.Id.ToString(); - } - - String extension = "CSV".Equals(file.Format) ? ".csv" : ".xml"; - - return fileName + extension; - } - } -} diff --git a/dotnet/v3.4/Reports/FindAndDownloadFile.cs b/dotnet/v3.4/Reports/FindAndDownloadFile.cs deleted file mode 100644 index eb80c85..0000000 --- a/dotnet/v3.4/Reports/FindAndDownloadFile.cs +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2018 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example provides an end-to-end example of how to find and download a - /// report file. - /// - class FindAndDownloadFile: SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example provides an end-to-end example of how to find " + - "and download a report file.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new FindAndDownloadFile(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - long reportId = long.Parse(_T("INSERT_REPORT_ID_HERE")); - - // 1. Find a file to download. - File file = FindFile(service, profileId, reportId); - - if (file != null) { - // 2. (optional) Generate browser URL. - GenerateBrowserUrl(service, reportId, file.Id.Value); - - // 3. Directly download the file - DirectDownloadFile(service, reportId, file.Id.Value); - } else { - Console.WriteLine( - "No file found for profile ID {0} and report ID {1}.", - profileId, reportId); - } - } - - private File FindFile(DfareportingService service, long profileId, - long reportId) { - File target = null; - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - ReportsResource.FilesResource.ListRequest request = - service.Reports.Files.List(profileId, reportId); - request.PageToken = nextPageToken; - files = request.Execute(); - - foreach (File file in files.Items) { - if (IsTargetFile(file)) { - target = file; - break; - } - } - - // Update the next page token. - nextPageToken = files.NextPageToken; - } while (target == null - && files.Items.Any() - && !String.IsNullOrEmpty(nextPageToken)); - - if (target != null) { - Console.WriteLine("Found file {0} with filename \"{1}\".", - target.Id, target.FileName); - return target; - } - - Console.WriteLine( - "Unable to find file for profile ID {0} and report ID {1}.", - profileId, reportId); - return null; - } - - private bool IsTargetFile(File file) { - // Provide custom validation logic here. - // For example purposes, any file with REPORT_AVAILABLE status is - // considered valid. - return "REPORT_AVAILABLE".Equals(file.Status); - } - - private void GenerateBrowserUrl(DfareportingService service, long reportId, - long fileId) { - File file = service.Files.Get(reportId, fileId).Execute(); - String browserUrl = file.Urls.BrowserUrl; - - Console.WriteLine("File {0} has browser URL: {1}.", file.Id, browserUrl); - } - - private void DirectDownloadFile(DfareportingService service, long reportId, - long fileId) { - // Retrieve the file metadata. - File file = service.Files.Get(reportId, fileId).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - // Create a get request. - FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize; - - // Execute the get request and download the file. - using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file), - System.IO.FileMode.Create, System.IO.FileAccess.Write)) { - getRequest.Download(outFile); - Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name); - } - } - } - - private string GenerateFileName(File file) { - // If no filename is specified, use the file ID instead. - string fileName = file.FileName; - if (String.IsNullOrEmpty(fileName)) { - fileName = file.Id.ToString(); - } - - String extension = "CSV".Equals(file.Format) ? ".csv" : ".xml"; - - return fileName + extension; - } - } -} diff --git a/dotnet/v3.4/Reports/FindAndRunReport.cs b/dotnet/v3.4/Reports/FindAndRunReport.cs deleted file mode 100644 index e063e0a..0000000 --- a/dotnet/v3.4/Reports/FindAndRunReport.cs +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2018 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using System.Threading; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example provides an end-to-end example of how to find and run a - /// report. - /// - class FindAndRunReport : SampleBase { - // The following values control retry behavior while the report is processing. - // Minimum amount of time between polling requests. Defaults to 10 seconds. - private static int MIN_RETRY_INTERVAL = 10; - // Maximum amount of time between polling requests. Defaults to 10 minutes. - private static int MAX_RETRY_INTERVAL = 10 * 60; - // Maximum amount of time to spend polling. Defaults to 1 hour. - private static int MAX_RETRY_ELAPSED_TIME = 60 * 60; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example provides an end-to-end example of how to find " + - "and run a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new FindAndRunReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // 1. Find a report to run. - Report report = FindReport(service, profileId); - - if (report != null) { - // 2. Run the report. - File file = RunReport(service, profileId, report.Id.Value); - - // 3. Wait for the report file to be ready. - WaitForReportFile(service, report.Id.Value, file.Id.Value); - } else { - Console.WriteLine("No report found for profile ID {0}.", profileId); - } - } - - private Report FindReport(DfareportingService service, long profileId) { - Report target = null; - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the reports list request. - ReportsResource.ListRequest request = service.Reports.List(profileId); - request.PageToken = nextPageToken; - reports = request.Execute(); - - foreach (Report report in reports.Items) { - if (IsTargetReport(report)) { - target = report; - break; - } - } - - // Update the next page token. - nextPageToken = reports.NextPageToken; - } while (target == null - && reports.Items.Any() - && !String.IsNullOrEmpty(nextPageToken)); - - if (target != null) { - Console.WriteLine("Found report {0} with name \"{1}\".", - target.Id, target.Name); - return target; - } - - Console.WriteLine("Unable to find report for profile ID {0}.", profileId); - return null; - } - - private bool IsTargetReport(Report report) { - // Provide custom validation logic here. - // For example purposes, any report is considered valid. - return true; - } - - private File RunReport(DfareportingService service, long profileId, - long reportId) { - // Run the report. - File file = service.Reports.Run(profileId, reportId).Execute(); - - Console.WriteLine("Running report {0}, current file status is {1}.", - reportId, file.Status); - return file; - } - - private void WaitForReportFile(DfareportingService service, long reportId, - long fileId) { - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve quota. - int sleep = 0; - int startTime = GetCurrentTimeInSeconds(); - do { - File file = service.Files.Get(reportId, fileId).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - Console.WriteLine("File status is {0}, ready to download.", file.Status); - return; - } else if (!"PROCESSING".Equals(file.Status)) { - Console.WriteLine("File status is {0}, processing failed.", file.Status); - return; - } else if (GetCurrentTimeInSeconds() - startTime > MAX_RETRY_ELAPSED_TIME) { - Console.WriteLine("File processing deadline exceeded."); - return; - } - - sleep = GetNextSleepInterval(sleep); - Console.WriteLine("File status is {0}, sleeping for {1} seconds.", file.Status, sleep); - Thread.Sleep(sleep * 1000); - } while (true); - } - - private int GetCurrentTimeInSeconds() { - return (int) (DateTime.Now.Ticks / TimeSpan.TicksPerSecond); - } - - private int GetNextSleepInterval(int previousSleepInterval) { - int minInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval); - int maxInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval * 3); - return Math.Min(MAX_RETRY_INTERVAL, new Random().Next(minInterval, maxInterval)); - } - } -} diff --git a/dotnet/v3.4/Reports/GetCompatibleFields.cs b/dotnet/v3.4/Reports/GetCompatibleFields.cs deleted file mode 100755 index 68f5118..0000000 --- a/dotnet/v3.4/Reports/GetCompatibleFields.cs +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get the compatible fields for a standard - /// report. - /// - class GetCompatibleFields : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get the compatible fields" + - " for a standard report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCompatibleFields(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("ENTER_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Retrieve the specified report. - Report report = service.Reports.Get(profileId, reportId).Execute(); - - // Look up the compatible fields for the report. - CompatibleFields fields = - service.Reports.CompatibleFields.Query(report, profileId).Execute(); - - // Display the compatible fields, assuming this is a standard report. - ReportCompatibleFields reportFields = fields.ReportCompatibleFields; - - Console.WriteLine("Compatible dimensions:\n"); - printDimensionNames(reportFields.Dimensions); - - Console.WriteLine("\nCompatible metrics:\n"); - printMetricNames(reportFields.Metrics); - - Console.WriteLine("\nCompatible dimension filters:\n"); - printDimensionNames(reportFields.DimensionFilters); - - Console.WriteLine("\nCompatible pivoted activity metrics:\n"); - printMetricNames(reportFields.PivotedActivityMetrics); - } - - private static void printDimensionNames(IList dimensions) { - foreach (Dimension dimension in dimensions) { - Console.WriteLine(dimension.Name); - } - } - - private static void printMetricNames(IList metrics) { - foreach (Metric metric in metrics) { - Console.WriteLine(metric.Name); - } - } - } -} diff --git a/dotnet/v3.4/Reports/GetDimensionValues.cs b/dotnet/v3.4/Reports/GetDimensionValues.cs deleted file mode 100755 index f1a0ccf..0000000 --- a/dotnet/v3.4/Reports/GetDimensionValues.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get all dimension values for a dimension. - /// - class GetDimensionValues : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get all dimension values for" + - " a dimension.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetDimensionValues(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(id,value)"; - - // Construct the dimension value request. - DimensionValueRequest request = new DimensionValueRequest(); - request.DimensionName = "advertiser"; - - // Set the date range from 1 year ago until today. - request.StartDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now.AddYears(-1)); - request.EndDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now); - - DimensionValueList values; - String nextPageToken = null; - - do { - // Create and execute the dimension value query request. - DimensionValuesResource.QueryRequest query = - service.DimensionValues.Query(request, profileId); - query.Fields = fields; - query.PageToken = nextPageToken; - values = query.Execute(); - - foreach (DimensionValue value in values.Items) { - Console.WriteLine("Dimension value with ID {0} and value \"{1}\" was found.", - value.Id, value.Value); - } - - // Update the next page token. - nextPageToken = values.NextPageToken; - } while (values.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Reports/GetFiles.cs b/dotnet/v3.4/Reports/GetFiles.cs deleted file mode 100755 index 0e60e50..0000000 --- a/dotnet/v3.4/Reports/GetFiles.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all the files for a profile. - /// - class GetFiles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all the files" + - " for a profile.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetFiles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - FilesResource.ListRequest request = service.Files.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - files = request.Execute(); - - foreach (File file in files.Items) { - Console.WriteLine("Report file with ID {0} and file name \"{1}\" has status \"{2}\".", - file.Id, file.FileName, file.Status); - } - - // Update the next page token. - nextPageToken = files.NextPageToken; - } while (files.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Reports/GetReportFiles.cs b/dotnet/v3.4/Reports/GetReportFiles.cs deleted file mode 100755 index e1bb6ee..0000000 --- a/dotnet/v3.4/Reports/GetReportFiles.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all the files for a report. - /// - class GetReportFiles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all the files" + - " for a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetReportFiles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("INSERT_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the report files list request. - ReportsResource.FilesResource.ListRequest request = - service.Reports.Files.List(profileId, reportId); - request.Fields = fields; - request.PageToken = nextPageToken; - files = request.Execute(); - - foreach (File file in files.Items) { - Console.WriteLine("Report file with ID {0} and file name \"{1}\" has status \"{2}\".", - file.Id, file.FileName, file.Status); - } - - // Update the next page token. - nextPageToken = files.NextPageToken; - } while (files.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Reports/GetReports.cs b/dotnet/v3.4/Reports/GetReports.cs deleted file mode 100755 index 8166eaa..0000000 --- a/dotnet/v3.4/Reports/GetReports.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all reports. - /// - class GetReports : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all reports.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetReports(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(id,name,type)"; - - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the report list request. - ReportsResource.ListRequest request = service.Reports.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - reports = request.Execute(); - - foreach (Report report in reports.Items) { - Console.WriteLine("{0} report with ID {1} and name \"{2}\" was found.", - report.Type, report.Id, report.Name); - } - - // Update the next page token. - nextPageToken = reports.NextPageToken; - } while (reports.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Reports/RunReport.cs b/dotnet/v3.4/Reports/RunReport.cs deleted file mode 100755 index 0fee520..0000000 --- a/dotnet/v3.4/Reports/RunReport.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Threading; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to run a report. - /// - class RunReport : SampleBase { - // The following values control retry behavior while the report is processing. - // Minimum amount of time between polling requests. Defaults to 10 seconds. - private static int MIN_RETRY_INTERVAL = 10; - // Maximum amount of time between polling requests. Defaults to 10 minutes. - private static int MAX_RETRY_INTERVAL = 10 * 60; - // Maximum amount of time to spend polling. Defaults to 1 hour. - private static int MAX_RETRY_ELAPSED_TIME = 60 * 60; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to run a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new RunReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("INSERT_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Run the report. - File file = service.Reports.Run(profileId, reportId).Execute(); - Console.WriteLine("File with ID {0} has been created.", file.Id); - - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve quota. - int sleep = 0; - int startTime = GetCurrentTimeInSeconds(); - do { - file = service.Files.Get(file.ReportId.Value, file.Id.Value).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - Console.WriteLine("File status is {0}, ready to download.", file.Status); - return; - } else if (!"PROCESSING".Equals(file.Status)) { - Console.WriteLine("File status is {0}, processing failed.", file.Status); - return; - } else if (GetCurrentTimeInSeconds() - startTime > MAX_RETRY_ELAPSED_TIME) { - Console.WriteLine("File processing deadline exceeded."); - return; - } - - sleep = GetNextSleepInterval(sleep); - Console.WriteLine("File status is {0}, sleeping for {1} seconds.", file.Status, sleep); - Thread.Sleep(sleep * 1000); - } while (true); - } - - private int GetCurrentTimeInSeconds() { - return (int) (DateTime.Now.Ticks / TimeSpan.TicksPerSecond); - } - - private int GetNextSleepInterval(int previousSleepInterval) { - int minInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval); - int maxInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval * 3); - return Math.Min(MAX_RETRY_INTERVAL, new Random().Next(minInterval, maxInterval)); - } - } -} diff --git a/dotnet/v3.4/SampleBase.cs b/dotnet/v3.4/SampleBase.cs deleted file mode 100755 index 903a467..0000000 --- a/dotnet/v3.4/SampleBase.cs +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -// Comment out the following define to make the samples non-interactive. -// This will require you to manually replace the INSERT_XXX fields in -// samples. -#define INTERACTIVE - -using System; -using Google.Apis.Dfareporting.v3_4; - -namespace DfaReporting.Samples { - /// - /// This abstract class represents a code example. - /// - abstract class SampleBase { - /// - /// Returns a description about the code example. - /// - public abstract string Description { - get; - } - - /// - /// Run the code example. - /// - /// A Dfa Reporting service instance. - public abstract void Run(DfareportingService service); - - protected string _T(string prompt) { -#if INTERACTIVE - Console.Write(prompt + " : "); - return Console.ReadLine(); -#else - return prompt; -#endif - } - } -} diff --git a/dotnet/v3.4/Subaccounts/CreateSubaccount.cs b/dotnet/v3.4/Subaccounts/CreateSubaccount.cs deleted file mode 100755 index 31f78a4..0000000 --- a/dotnet/v3.4/Subaccounts/CreateSubaccount.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a subaccount in a given DoubleClick Campaign Manager - /// account. To get the available permissions, run - /// GetUserRolePermissions.cs. - /// - class CreateSubaccount : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a subaccount in a given DoubleClick" + - " Campaign Manager account. To get the available permissions, run" + - " GetSubaccountPermissions.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateSubaccount(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long accountId = long.Parse(_T("INSERT_ACCOUNT_ID_HERE")); - long permissionOneId = long.Parse(_T("INSERT_FIRST_PERMISSION_ID_HERE")); - long permissionTwoId = long.Parse(_T("INSERT_SECOND_PERMISSION_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String subaccountName = _T("INSERT_SUBACCOUNT_NAME_HERE"); - - // Create subaccount structure. - Subaccount subaccount = new Subaccount(); - subaccount.Name = subaccountName; - subaccount.AccountId = accountId; - - // Create a collection of all permissions assigned to this subaccount and add it to the - // subaccount structure. To get list of available permissions, run GetUserRolePermissions.cs. - subaccount.AvailablePermissionIds = new List { permissionOneId, permissionTwoId }; - - // Create subaccount. - Subaccount result = service.Subaccounts.Insert(subaccount, profileId).Execute(); - - // Display subaccount ID. - Console.WriteLine("Subaccount with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Subaccounts/GetSubaccountPermissions.cs b/dotnet/v3.4/Subaccounts/GetSubaccountPermissions.cs deleted file mode 100755 index 508fca6..0000000 --- a/dotnet/v3.4/Subaccounts/GetSubaccountPermissions.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all of the available subaccount permissions. - /// - /// To get a subaccount ID, run GetSubaccounts.cs. - /// - class GetSubaccountPermissions : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all of the available user role permissions for the" + - " specified subaccount.\n\nTo get a subaccount ID, run GetSubaccounts.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSubaccountPermissions(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - long subaccountId = long.Parse(_T("INSERT_SUBACCOUNT_ID_HERE")); - - // Limit the fields returned. - String fields = "userRolePermissions(id,name)"; - - // Retrieve the subaccount. - Subaccount subaccount = service.Subaccounts.Get(profileId, subaccountId).Execute(); - - // Retrieve the subaccount permissions. - UserRolePermissionsResource.ListRequest request = service.UserRolePermissions.List(profileId); - request.Ids = subaccount.AvailablePermissionIds.Select(p => p.ToString()).ToList(); - request.Fields = fields; - - UserRolePermissionsListResponse permissions = request.Execute(); - - // Display the subaccount permissions. - foreach (UserRolePermission permission in permissions.UserRolePermissions) { - Console.WriteLine("User role permission with ID {0} and name \"{1}\" was found.", - permission.Id, permission.Name); - } - } - } -} diff --git a/dotnet/v3.4/Subaccounts/GetSubaccounts.cs b/dotnet/v3.4/Subaccounts/GetSubaccounts.cs deleted file mode 100755 index 8c546b5..0000000 --- a/dotnet/v3.4/Subaccounts/GetSubaccounts.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all subaccounts. - /// - /// Note that the permissions assigned to a subaccount are not returned in a - /// human-readable format with this example. Run GetUserRolePermissions.cs - /// to see what permissions are available on a subaccount. - /// - class GetSubaccounts : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all subaccounts.\n\n" + - "Note that the permissions assigned to a subaccount are not returned" + - " in a human-readable format with this example. Run" + - " GetUserRolePermissions.cs to see what permissions are available" + - " on a subaccount.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSubaccounts(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,subaccounts(id,name)"; - - SubaccountsListResponse subaccounts; - String nextPageToken = null; - - do { - // Create and execute the subaccounts list request. - SubaccountsResource.ListRequest request = service.Subaccounts.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - subaccounts = request.Execute(); - - foreach (Subaccount subaccount in subaccounts.Subaccounts) { - Console.WriteLine("Subaccount with ID {0} and name \"{1}\" was found.", subaccount.Id, - subaccount.Name); - } - - // Update the next page token. - nextPageToken = subaccounts.NextPageToken; - } while (subaccounts.Subaccounts.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/Targeting/ConfigureDynamicAssetTargeting.cs b/dotnet/v3.4/Targeting/ConfigureDynamicAssetTargeting.cs deleted file mode 100755 index 7aaa40e..0000000 --- a/dotnet/v3.4/Targeting/ConfigureDynamicAssetTargeting.cs +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads a new video asset to an existing in-stream video creative and configures - /// dynamic asset selection, using a specified targeting template. To get an in-stream video - /// creative, run CreateInstreamVideoCreative.cs. To get a targeting template, run - /// CreateTargetingTemplate.cs. - /// - class ConfigureDynamicAssetTargeting : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads a new video asset to an existing in-stream video creative " + - "and configures dynamic asset selection, using a specified targeting template. To " + - "get an in-stream video creative, run CreateInstreamVideoCreative.cs. To get a " + - "targeting template, run CreateTargetingTemplate.cs."; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new ConfigureDynamicAssetTargeting(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long instreamVideoCreativeId = long.Parse(_T("INSERT_INSTREAM_VIDEO_CREATIVE_ID_HERE")); - long targetingTemplateId = long.Parse(_T("INSERT_TARGETING_TEMPLATE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string videoAssetName = _T("INSERT_VIDEO_ASSET_NAME_HERE"); - string pathToVideoAssetFile = _T("INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"); - - // Retrieve the specified creative. - Creative creative = service.Creatives.Get(profileId, instreamVideoCreativeId).Execute(); - if (creative == null || !"INSTREAM_VIDEO".Equals(creative.Type)) { - Console.Error.WriteLine("Invalid creative specified."); - return; - } - - CreativeAssetSelection selection = creative.CreativeAssetSelection; - if (!creative.DynamicAssetSelection.Value) { - // Locate an existing video asset to use as a default. - // This example uses the first PARENT_VIDEO asset found. - CreativeAsset defaultAsset = - creative.CreativeAssets.First(asset => "PARENT_VIDEO".Equals(asset.Role)); - if (defaultAsset == null) { - Console.Error.WriteLine("Default video asset could not be found."); - return; - } - - // Create a new selection using the existing asset as a default. - selection = new CreativeAssetSelection(); - selection.DefaultAssetId = defaultAsset.Id; - selection.Rules = new List(); - - // Enable dynamic asset selection for the creative. - creative.DynamicAssetSelection = true; - creative.CreativeAssetSelection = selection; - } - - // Upload the new video asset and add it to the creative. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, - creative.AdvertiserId.Value); - CreativeAssetMetadata videoMetadata = assetUtils.uploadAsset(pathToVideoAssetFile, "VIDEO"); - creative.CreativeAssets.Add(new CreativeAsset() { - AssetIdentifier = videoMetadata.AssetIdentifier, - Role = "PARENT_VIDEO" - }); - - // Create a rule targeting the new video asset and add it to the selection. - Rule rule = new Rule(); - rule.AssetId = videoMetadata.Id; - rule.Name = "Test rule for asset " + videoMetadata.Id; - rule.TargetingTemplateId = targetingTemplateId; - selection.Rules.Add(rule); - - // Update the creative. - Creative result = service.Creatives.Update(creative, profileId).Execute(); - Console.WriteLine("Dynamic asset selection enabled for creative with ID {0}.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Targeting/CreateTargetingTemplate.cs b/dotnet/v3.4/Targeting/CreateTargetingTemplate.cs deleted file mode 100755 index 643b6a8..0000000 --- a/dotnet/v3.4/Targeting/CreateTargetingTemplate.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a basic targeting template associated with a given advertiser. To get an - /// advertiser ID, run GetAdvertisers.cs. - /// - class CreateTargetingTemplate : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a basic targeting template associated with a given " + - "advertiser. To get an advertiser ID, run GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateTargetingTemplate(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string targetingTemplateName = _T("INSERT_TARGETING_TEMPLATE_NAME_HERE"); - - // Create the targeting template. - TargetingTemplate template = new TargetingTemplate(); - template.AdvertiserId = advertiserId; - template.Name = targetingTemplateName; - - // Configure the template to serve ads on Monday, Wednesday, and Friday from 9-10am - // and 3-5pm. - DayPartTargeting dayTargeting = new DayPartTargeting(); - dayTargeting.DaysOfWeek = new List() { "MONDAY", "WEDNESDAY", "FRIDAY" }; - dayTargeting.HoursOfDay = new List() { 9, 15, 16 }; - dayTargeting.UserLocalTime = true; - template.DayPartTargeting = dayTargeting; - - // Insert the targeting template. - TargetingTemplate result = service.TargetingTemplates.Insert(template, profileId).Execute(); - - // Display the new targeting template ID. - Console.WriteLine("Targeting template with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/Targeting/GetTargetingTemplates.cs b/dotnet/v3.4/Targeting/GetTargetingTemplates.cs deleted file mode 100755 index 344c99d..0000000 --- a/dotnet/v3.4/Targeting/GetTargetingTemplates.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the name, ID and advertiser ID for every targeting template your DCM - /// user profile can see. - /// - class GetTargetingTemplates : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the name, ID and advertiser ID for every targeting " + - "template your DCM user profile can see.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetTargetingTemplates(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,targetingTemplates(advertiserId,id,name)"; - - TargetingTemplatesListResponse templates; - String nextPageToken = null; - - do { - // Create and execute the placements list request - TargetingTemplatesResource.ListRequest request = - service.TargetingTemplates.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - templates = request.Execute(); - - foreach (TargetingTemplate template in templates.TargetingTemplates) { - Console.WriteLine( - "Targeting template {0} and name \"{1}\" is associated with advertiser ID {2}.", - template.Id, template.Name, template.AdvertiserId); - } - - // Update the next page token - nextPageToken = templates.NextPageToken; - } while (templates.TargetingTemplates.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/UserProfiles/GetUserProfiles.cs b/dotnet/v3.4/UserProfiles/GetUserProfiles.cs deleted file mode 100755 index 1e9f424..0000000 --- a/dotnet/v3.4/UserProfiles/GetUserProfiles.cs +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all user profiles. - /// - class GetUserProfiles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all user profiles.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetUserProfiles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = service.UserProfiles.List().Execute(); - foreach (UserProfile profile in profiles.Items) { - Console.WriteLine("User profile with ID {0} and name \"{1}\" was found for account {2}.", - profile.ProfileId, profile.UserName, profile.AccountId); - } - } - } -} diff --git a/dotnet/v3.4/UserRoles/CreateUserRole.cs b/dotnet/v3.4/UserRoles/CreateUserRole.cs deleted file mode 100755 index cd2748d..0000000 --- a/dotnet/v3.4/UserRoles/CreateUserRole.cs +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a user role in a given DoubleClick Campaign Manager - /// subaccount. To get the subaccount ID, run GetSubaccounts.cs. To get the - /// available permissions, run GetUserRolePermissions.cs. To get the parent - /// user role ID, run GetUserRoles.cs. - /// - class CreateUserRole : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a user role in a given DoubleClick" + - " Campaign Manager subaccount. To get the subaccount ID, run" + - " GetSubaccounts.cs. To get the available permissions, run" + - " GetUserRolePermissions.cs. To get the parent user role ID, run" + - " GetUserRoles.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateUserRole(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long parentUserRoleId = long.Parse(_T("INSERT_PARENT_USER_ROLE_ID_HERE")); - long permission1Id = long.Parse(_T("INSERT_FIRST_PERMISSION_ID_HERE")); - long permission2Id = long.Parse(_T("INSERT_SECOND_PERMISSIONS_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - long subaccountId = long.Parse(_T("INSERT_SUBACCOUNT_ID_HERE")); - - String userRoleName = _T("INSERT_USER_ROLE_NAME_HERE"); - - // Create user role structure. - UserRole userRole = new UserRole(); - userRole.Name = userRoleName; - userRole.SubaccountId = subaccountId; - userRole.ParentUserRoleId = parentUserRoleId; - - // Create a permission object to represent each permission this user role - // has. - UserRolePermission permission1 = new UserRolePermission(); - permission1.Id = permission1Id; - UserRolePermission permission2 = new UserRolePermission(); - permission2.Id = permission2Id; - List permissions = - new List { permission1, permission2 }; - - // Add the permissions to the user role. - userRole.Permissions = permissions; - - // Create user role. - UserRole result = service.UserRoles.Insert(userRole, profileId).Execute(); - - // Display user role ID. - Console.WriteLine("User role with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.4/UserRoles/GetUserRoles.cs b/dotnet/v3.4/UserRoles/GetUserRoles.cs deleted file mode 100755 index 940043e..0000000 --- a/dotnet/v3.4/UserRoles/GetUserRoles.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_4; -using Google.Apis.Dfareporting.v3_4.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all user roles. - /// - /// The output is limited to include only ID, name, account ID and subaccount ID. - /// - class GetUserRoles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all user roles.\n\n" + - "The output is limited to include only ID, name, account ID and" + - " subaccount ID.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetUserRoles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,userRoles(accountId,id,name,subaccountId)"; - - UserRolesListResponse roles; - String nextPageToken = null; - - do { - // Create and execute the user roles list request. - UserRolesResource.ListRequest request = service.UserRoles.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - - roles = request.Execute(); - - foreach (UserRole role in roles.UserRoles) { - Console.WriteLine("User role with ID {0} and name \"{1}\" was found.", role.Id, - role.Name); - } - - // Update the next page token. - nextPageToken = roles.NextPageToken; - } while (roles.UserRoles.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.4/app.config b/dotnet/v3.4/app.config deleted file mode 100755 index 87fd34f..0000000 --- a/dotnet/v3.4/app.config +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dotnet/v3.4/client_secrets.json b/dotnet/v3.4/client_secrets.json deleted file mode 100755 index 63d282d..0000000 --- a/dotnet/v3.4/client_secrets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "installed": { - "client_id": "Enter Client ID", - "client_secret": "Enter Client Secret" - } -} \ No newline at end of file diff --git a/dotnet/v3.4/packages.config b/dotnet/v3.4/packages.config deleted file mode 100644 index e8b0403..0000000 --- a/dotnet/v3.4/packages.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/dotnet/v3.5/Ads/CreateRotationGroup.cs b/dotnet/v3.5/Ads/CreateRotationGroup.cs deleted file mode 100755 index 87b2669..0000000 --- a/dotnet/v3.5/Ads/CreateRotationGroup.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a rotation group ad in a given campaign. Start and - /// end date for the ad must be within campaign start and end dates. To - /// create creatives, run one of the Create*Creative.cs examples. To get - /// available placements, run GetPlacements.cs. - /// - class CreateRotationGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a rotation group ad in a given campaign." + - " Start and end date for the ad must be within campaign start and" + - " end dates. To create creatives, run one of the Create*Creative.cs" + - " examples. To get available placements, run GetPlacements.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateRotationGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long creativeId = long.Parse(_T("INSERT_CREATIVE_ID_HERE")); - long placementId = long.Parse(_T("INSERT_PLACEMENT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - String adName = _T("INSERT_AD_NAME_HERE"); - - // Retrieve the campaign. - Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute(); - - // Create a click-through URL. - ClickThroughUrl clickThroughUrl = new ClickThroughUrl(); - clickThroughUrl.DefaultLandingPage = true; - - // Create a creative assignment. - CreativeAssignment creativeAssignment = new CreativeAssignment(); - creativeAssignment.Active = true; - creativeAssignment.CreativeId = creativeId; - creativeAssignment.ClickThroughUrl = clickThroughUrl; - - // Create a placement assignment. - PlacementAssignment placementAssignment = new PlacementAssignment(); - placementAssignment.Active = true; - placementAssignment.PlacementId = placementId; - - // Create a creative rotation. - CreativeRotation creativeRotation = new CreativeRotation(); - creativeRotation.CreativeAssignments = new List() { - creativeAssignment - }; - - // Create a delivery schedule. - DeliverySchedule deliverySchedule = new DeliverySchedule(); - deliverySchedule.ImpressionRatio = 1; - deliverySchedule.Priority = "AD_PRIORITY_01"; - - DateTime startDate = DateTime.Now; - DateTime endDate = Convert.ToDateTime(campaign.EndDate); - - // Create a rotation group. - Ad rotationGroup = new Ad(); - rotationGroup.Active = true; - rotationGroup.CampaignId = campaignId; - rotationGroup.CreativeRotation = creativeRotation; - rotationGroup.DeliverySchedule = deliverySchedule; - rotationGroup.StartTime = startDate; - rotationGroup.EndTime = endDate; - rotationGroup.Name = adName; - rotationGroup.PlacementAssignments = new List() { - placementAssignment - }; - rotationGroup.Type = "AD_SERVING_STANDARD_AD"; - - // Insert the rotation group. - Ad result = service.Ads.Insert(rotationGroup, profileId).Execute(); - - // Display the new ad ID. - Console.WriteLine("Ad with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Ads/GetAds.cs b/dotnet/v3.5/Ads/GetAds.cs deleted file mode 100755 index b1e3ff9..0000000 --- a/dotnet/v3.5/Ads/GetAds.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the name, ID and advertiser ID for every active ad - /// your DFA user profile can see. - /// - class GetAds : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the name, ID and advertiser ID for" + - " every active ad.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAds(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,ads(advertiserId,id,name)"; - - AdsListResponse result; - String nextPageToken = null; - - do { - // Create and execute the ad list request. - AdsResource.ListRequest request = service.Ads.List(profileId); - request.Active = true; - request.Fields = fields; - request.PageToken = nextPageToken; - result = request.Execute(); - - foreach (Ad ad in result.Ads) { - Console.WriteLine( - "Ad with ID {0} and name \"{1}\" is associated with advertiser" + - " ID {2}.", ad.Id, ad.Name, ad.AdvertiserId); - } - - // Update the next page token. - nextPageToken = result.NextPageToken; - } while (result.Ads.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Advertisers/AssignAdvertisersToAdvertiserGroup.cs b/dotnet/v3.5/Advertisers/AssignAdvertisersToAdvertiserGroup.cs deleted file mode 100755 index c711b23..0000000 --- a/dotnet/v3.5/Advertisers/AssignAdvertisersToAdvertiserGroup.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example assigns an advertiser to an advertiser group. - /// - /// CAUTION: An advertiser that has campaigns associated with it cannot be removed from an - /// advertiser group once assigned. - /// - class AssignAdvertisersToAdvertiserGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example assigns an advertiser to an advertiser group." + - "\n\nCAUTION: An advertiser that has campaigns associated with it" + - " cannot be removed from an advertiser group once assigned.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AssignAdvertisersToAdvertiserGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long advertiserGroupId = long.Parse(_T("INSERT_ADVERTISER_GROUP_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Create the Advertiser and populate with the group ID to patch. - Advertiser advertiser = new Advertiser(); - advertiser.AdvertiserGroupId = advertiserGroupId; - - // Patch the existing advertiser. - Advertiser result = - service.Advertisers.Patch(advertiser, profileId, advertiserId).Execute(); - - // Print out the advertiser and advertiser group ID. - Console.WriteLine("Advertiser with ID {0} was assigned to advertiser" + - " group \"{1}\".", result.Id, result.AdvertiserGroupId); - } - } -} diff --git a/dotnet/v3.5/Advertisers/CreateAdvertiser.cs b/dotnet/v3.5/Advertisers/CreateAdvertiser.cs deleted file mode 100755 index d44504a..0000000 --- a/dotnet/v3.5/Advertisers/CreateAdvertiser.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an advertiser in a given DCM account. To get - /// advertisers, see GetAdvertisers.cs. - /// - class CreateAdvertiser : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an advertiser in a given DCM account. To" + - " get advertisers, see GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateAdvertiser(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String advertiserName = _T("INSERT_ADVERTISER_NAME_HERE"); - - // Create the advertiser structure. - Advertiser advertiser = new Advertiser(); - advertiser.Name = advertiserName; - advertiser.Status = "APPROVED"; - - // Create the advertiser. - Advertiser result = service.Advertisers.Insert(advertiser, profileId).Execute(); - - // Display the advertiser ID. - Console.WriteLine("Advertiser with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Advertisers/CreateAdvertiserGroup.cs b/dotnet/v3.5/Advertisers/CreateAdvertiserGroup.cs deleted file mode 100755 index 7460c3c..0000000 --- a/dotnet/v3.5/Advertisers/CreateAdvertiserGroup.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an advertiser group. To get advertiser groups, see - /// GetAdvertiserGroups.cs. - /// - class CreateAdvertiserGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an advertiser group. To get advertiser" + - " groups, see GetAdvertiserGroups.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateAdvertiserGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String advertiserGroupName = _T("INSERT_ADVERTISER_GROUP_NAME_HERE"); - - // Create advertiser group structure. - AdvertiserGroup advertiserGroup = new AdvertiserGroup(); - advertiserGroup.Name = advertiserGroupName; - - // Create advertiser group. - AdvertiserGroup result = - service.AdvertiserGroups.Insert(advertiserGroup, profileId).Execute(); - - // Display advertiser group ID. - Console.WriteLine("Advertiser Group with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Advertisers/CreateAdvertiserLandingPage.cs b/dotnet/v3.5/Advertisers/CreateAdvertiserLandingPage.cs deleted file mode 100755 index 81a38d4..0000000 --- a/dotnet/v3.5/Advertisers/CreateAdvertiserLandingPage.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an advertiser landing page. - /// - class CreateAdvertiserLandingPage : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an advertiser landing page."; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateAdvertiserLandingPage(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String landingPageName = _T("INSERT_LANDING_PAGE_NAME_HERE"); - String landingPageUrl = _T("INSERT_LANDING_PAGE_URL_HERE"); - - // Create the landing page structure. - LandingPage landingPage = new LandingPage(); - landingPage.AdvertiserId = advertiserId; - landingPage.Archived = false; - landingPage.Name = landingPageName; - landingPage.Url = landingPageUrl; - - // Create the landing page. - LandingPage result = service.AdvertiserLandingPages.Insert(landingPage, profileId).Execute(); - - // Display the landing page ID. - Console.WriteLine("Advertiser landing page with ID {0} and name \"{1}\" was created.", - result.Id, result.Name); - } - } -} diff --git a/dotnet/v3.5/Advertisers/GetAdvertiserGroups.cs b/dotnet/v3.5/Advertisers/GetAdvertiserGroups.cs deleted file mode 100755 index f49c89a..0000000 --- a/dotnet/v3.5/Advertisers/GetAdvertiserGroups.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all advertiser groups for the specified user - /// profile. - /// - class GetAdvertiserGroups : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all advertiser groups for the" + - " specified user profile.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAdvertiserGroups(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,advertiserGroups(id,name)"; - - // List all advertiser groups - AdvertiserGroupsResource.ListRequest request = - service.AdvertiserGroups.List(profileId); - request.Fields = fields; - AdvertiserGroupsListResponse result = request.Execute(); - - // Display advertiser group names and IDs - if (result.AdvertiserGroups.Any()) { - foreach (AdvertiserGroup group in result.AdvertiserGroups) { - Console.WriteLine("Advertiser Group with ID {0} and name \"{1}\"" + - " was found.", group.Id, group.Name); - } - } else { - Console.WriteLine("No advertiser groups found for your criteria."); - } - } - } -} diff --git a/dotnet/v3.5/Advertisers/GetAdvertiserLandingPages.cs b/dotnet/v3.5/Advertisers/GetAdvertiserLandingPages.cs deleted file mode 100755 index 2a4da77..0000000 --- a/dotnet/v3.5/Advertisers/GetAdvertiserLandingPages.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; -using System.Collections.Generic; - -namespace DfaReporting.Samples { - /// - /// This example lists all landing pages for a specified advertiser. - /// - class GetAdvertiserLandingPages : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all landing pages for a specified advertiser."; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAdvertiserLandingPages(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,landingPages(id,name,url)"; - - AdvertiserLandingPagesListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser landing pages list request. - AdvertiserLandingPagesResource.ListRequest request = - service.AdvertiserLandingPages.List(profileId); - request.AdvertiserIds = new List() { advertiserId.ToString() }; - request.Fields = fields; - request.PageToken = nextPageToken; - result = request.Execute(); - - foreach (LandingPage landingPage in result.LandingPages) { - Console.WriteLine("Advertiser landing page with ID {0}, name \"{1}\", and " + - "URL {2} was found.", landingPage.Id, landingPage.Name, landingPage.Url); - } - - // Update the next page token. - nextPageToken = result.NextPageToken; - } while (result.LandingPages.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Advertisers/GetAdvertisers.cs b/dotnet/v3.5/Advertisers/GetAdvertisers.cs deleted file mode 100755 index 2047eb4..0000000 --- a/dotnet/v3.5/Advertisers/GetAdvertisers.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the name, ID and spotlight configuration ID for - /// every advertiser your DCM user profile can see. - /// - class GetAdvertisers : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the name, ID and spotlight" + - " configuration ID for every advertiser your DCM user profile can" + - " see.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetAdvertisers(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,advertisers(id,floodlightConfigurationId,name)"; - - AdvertisersListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser list request. - AdvertisersResource.ListRequest request = service.Advertisers.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - result = request.Execute(); - - foreach (Advertiser advertiser in result.Advertisers) { - Console.WriteLine("Advertiser with ID {0}, name \"{1}\", and" + - " floodlight configuration ID {2} was found.", advertiser.Id, - advertiser.Name, advertiser.FloodlightConfigurationId); - } - - // Update the next page token. - nextPageToken = result.NextPageToken; - } while (result.Advertisers.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Auth/AuthenticateUsingServiceAccount.cs b/dotnet/v3.5/Auth/AuthenticateUsingServiceAccount.cs deleted file mode 100755 index 218d3d1..0000000 --- a/dotnet/v3.5/Auth/AuthenticateUsingServiceAccount.cs +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using Google.Apis.Auth.OAuth2; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; -using Google.Apis.Json; -using Google.Apis.Services; -using System; -using System.Collections.Generic; -using System.IO; - -namespace DfaReporting.Samples { - /// - /// This example demonstrates how to authenticate and make a basic request using a service - /// account. - /// - class AuthenticateUsingServiceAccount : SampleBase { - /// - /// The OAuth 2.0 scopes to request. - /// - private static readonly IEnumerable OAuthScopes = new[] { - DfareportingService.Scope.Dfareporting - }; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example demonstrates how to authenticate and make a basic request" + - " using a service account.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AuthenticateUsingServiceAccount(); - Console.WriteLine(codeExample.Description); - codeExample.Run(null); - } - - /// - /// Run the code example. - /// - /// Unused - public override void Run(DfareportingService service) { - string pathToJsonFile = _T("ENTER_PATH_TO_JSON_FILE_HERE"); - - // An optional Google account email to impersonate. Only applicable to service accounts which - // have enabled domain-wide delegation and wish to make API requests on behalf of an account - // within their domain. Setting this field will not allow you to impersonate a user from a - // domain you don't own (e.g., gmail.com). - string emailToImpersonate = _T(""); - - // Build service account credential. - ServiceAccountCredential credential = - getServiceAccountCredential(pathToJsonFile, emailToImpersonate); - - // Create a Dfareporting service object. - // - // Note: application name should be replaced with a value that identifies your application. - service = new DfareportingService( - new BaseClientService.Initializer { - HttpClientInitializer = credential, - ApplicationName = "C# service account sample" - } - ); - - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = service.UserProfiles.List().Execute(); - - foreach (UserProfile profile in profiles.Items) { - Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", - profile.ProfileId, profile.UserName); - } - } - - private ServiceAccountCredential getServiceAccountCredential(String pathToJsonFile, - String emailToImpersonate) { - // Load and deserialize credential parameters from the specified JSON file. - JsonCredentialParameters parameters; - using (Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) { - parameters = NewtonsoftJsonSerializer.Instance.Deserialize(json); - } - - // Create a credential initializer with the correct scopes. - ServiceAccountCredential.Initializer initializer = - new ServiceAccountCredential.Initializer(parameters.ClientEmail) { - Scopes = OAuthScopes - }; - - // Configure impersonation (if applicable). - if (!String.IsNullOrEmpty(emailToImpersonate)) { - initializer.User = emailToImpersonate; - } - - // Create a service account credential object using the deserialized private key. - ServiceAccountCredential credential = - new ServiceAccountCredential(initializer.FromPrivateKey(parameters.PrivateKey)); - - return credential; - } - } -} diff --git a/dotnet/v3.5/Auth/AuthenticateUsingUserAccount.cs b/dotnet/v3.5/Auth/AuthenticateUsingUserAccount.cs deleted file mode 100755 index 35270d1..0000000 --- a/dotnet/v3.5/Auth/AuthenticateUsingUserAccount.cs +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using Google.Apis.Auth.OAuth2; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; -using Google.Apis.Json; -using Google.Apis.Services; -using Google.Apis.Util.Store; -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace DfaReporting.Samples { - /// - /// This example demonstrates how to authenticate and make a basic request using a user account, - /// via the - /// installed application flow. - /// - class AuthenticateUsingUserAccount : SampleBase { - /// - /// The location where authorization credentials will be cached. - /// - private static readonly string DataStorePath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "DfaReporting.Auth.Sample"); - - /// - /// The OAuth 2.0 scopes to request. - /// - private static readonly IEnumerable OAuthScopes = new[] { - DfareportingService.Scope.Dfareporting - }; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example demonstrates how to authenticate and make a basic request using a" + - " user account, via the installed application flow.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AuthenticateUsingUserAccount(); - Console.WriteLine(codeExample.Description); - codeExample.Run(null); - } - - /// - /// Run the code example. - /// - /// Unused - public override void Run(DfareportingService service) { - string pathToJsonFile = _T("ENTER_PATH_TO_JSON_FILE_HERE"); - - // Build user account credential. - UserCredential credential = - getUserAccountCredential(pathToJsonFile, new FileDataStore(DataStorePath, true)); - - // Create a Dfareporting service object. - // - // Note: application name should be replaced with a value that identifies your application. - service = new DfareportingService( - new BaseClientService.Initializer { - HttpClientInitializer = credential, - ApplicationName = "C# installed app sample" - } - ); - - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = service.UserProfiles.List().Execute(); - - foreach (UserProfile profile in profiles.Items) { - Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", - profile.ProfileId, profile.UserName); - } - } - - private UserCredential getUserAccountCredential(String pathToJsonFile, IDataStore dataStore) { - // Load client secrets from the specified JSON file. - GoogleClientSecrets clientSecrets; - using(Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) { - clientSecrets = GoogleClientSecrets.Load(json); - } - - // Create an asynchronous authorization task. - // - // Note: providing a data store allows auth credentials to be cached, so they survive multiple - // runs of the application. This avoids prompting the user for authorization every time the - // access token expires, by remembering the refresh token. The "user" value is used to - // identify a specific set of credentials within the data store. You may provide different - // values here to persist credentials for multiple users to the same data store. - Task authorizationTask = GoogleWebAuthorizationBroker.AuthorizeAsync( - clientSecrets.Secrets, - OAuthScopes, - "user", - CancellationToken.None, - dataStore); - - // Authorize and persist credentials to the data store. - UserCredential credential = authorizationTask.Result; - - return credential; - } - } -} diff --git a/dotnet/v3.5/Campaigns/CreateCampaign.cs b/dotnet/v3.5/Campaigns/CreateCampaign.cs deleted file mode 100755 index bb5874c..0000000 --- a/dotnet/v3.5/Campaigns/CreateCampaign.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; -using System.Collections.Generic; - -namespace DfaReporting.Samples { - /// - /// This example creates a campaign associated with a given advertiser. To - /// create an advertiser, run CreateAdvertiser.cs. - /// - class CreateCampaign : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a campaign associated with a given" + - " advertiser. To create an advertiser, run CreateAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCampaign(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String campaignName = _T("INSERT_CAMPAIGN_NAME_HERE"); - - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(service, profileId, advertiserId); - - // Create the campaign structure. - Campaign campaign = new Campaign(); - campaign.Name = campaignName; - campaign.AdvertiserId = advertiserId; - campaign.Archived = false; - campaign.DefaultLandingPageId = defaultLandingPage.Id; - - // Set the campaign start date. This example uses today's date. - campaign.StartDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now); - - // Set the campaign end date. This example uses one month from today's date. - campaign.EndDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now.AddMonths(1)); - - // Insert the campaign. - Campaign result = service.Campaigns.Insert(campaign, profileId).Execute(); - - // Display the new campaign ID. - Console.WriteLine("Campaign with ID {0} was created.", result.Id); - } - - private LandingPage getAdvertiserLandingPage(DfareportingService service, long profileId, - long advertiserId) { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesResource.ListRequest listRequest = - service.AdvertiserLandingPages.List(profileId); - listRequest.AdvertiserIds = new List() { advertiserId.ToString() }; - listRequest.MaxResults = 1; - - AdvertiserLandingPagesListResponse landingPages = listRequest.Execute(); - - if (landingPages.LandingPages == null || landingPages.LandingPages.Count == 0) { - throw new InvalidOperationException( - String.Format("No landing pages found for advertiser with ID {0}.", advertiserId)); - } - - return landingPages.LandingPages[0]; - } - } -} diff --git a/dotnet/v3.5/Campaigns/CreateCampaignEventTag.cs b/dotnet/v3.5/Campaigns/CreateCampaignEventTag.cs deleted file mode 100755 index 57c0965..0000000 --- a/dotnet/v3.5/Campaigns/CreateCampaignEventTag.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates an event tag for the specified campaign. - /// - class CreateCampaignEventTag : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates an event tag for the specified campaign.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCampaignEventTag(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String eventTagName = _T("INSERT_EVENT_TAG_NAME_HERE"); - String eventTagUrl = _T("INSERT_EVENT_TAG_URL_HERE"); - - // Create the event tag structure. - EventTag eventTag = new EventTag(); - eventTag.CampaignId = campaignId; - eventTag.Name = eventTagName; - eventTag.Status = "ENABLED"; - eventTag.Type = "CLICK_THROUGH_EVENT_TAG"; - eventTag.Url = eventTagUrl; - - // Insert the campaign. - EventTag result = service.EventTags.Insert(eventTag, profileId).Execute(); - - // Display the new campaign ID. - Console.WriteLine("Event Tag with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Campaigns/GetCampaigns.cs b/dotnet/v3.5/Campaigns/GetCampaigns.cs deleted file mode 100755 index 8160ddd..0000000 --- a/dotnet/v3.5/Campaigns/GetCampaigns.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all existing campaigns for the specified user profile. - /// - class GetCampaigns : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all existing campaigns for the specified" + - " user profile.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCampaigns(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,campaigns(id,name)"; - - CampaignsListResponse campaigns; - String nextPageToken = null; - - do { - // Create and execute the campaigns list request. - CampaignsResource.ListRequest request = service.Campaigns.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - campaigns = request.Execute(); - - foreach (Campaign campaign in campaigns.Campaigns) { - Console.WriteLine("Campaign with ID {0} and name \"{1}\" was found.", - campaign.Id, campaign.Name); - } - - // Update the next page token. - nextPageToken = campaigns.NextPageToken; - } while (campaigns.Campaigns.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Conversions/InsertOfflineMobileConversion.cs b/dotnet/v3.5/Conversions/InsertOfflineMobileConversion.cs deleted file mode 100755 index 2fba9c0..0000000 --- a/dotnet/v3.5/Conversions/InsertOfflineMobileConversion.cs +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example inserts an offline conversion attributed to a mobile device ID. - /// - class InsertOfflineMobileConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example inserts an offline conversion attributed to a mobile device ID.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new InsertOfflineMobileConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string conversionMobileId = _T("INSERT_CONVERSION_MOBILE_ID_HERE"); - - // Generate a timestamp in milliseconds since Unix epoch. - TimeSpan timeStamp = DateTime.UtcNow - new DateTime(1970, 1, 1); - long currentTimeInMilliseconds = (long) timeStamp.TotalMilliseconds; - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Create the conversion. - Conversion conversion = new Conversion(); - conversion.MobileDeviceId = conversionMobileId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = currentTimeInMilliseconds.ToString(); - conversion.TimestampMicros = currentTimeInMilliseconds * 1000; - - // Insert the conversion. - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.Conversions = new List() { conversion }; - - ConversionsBatchInsertResponse response = - service.Conversions.Batchinsert(request, profileId).Execute(); - - // Handle the batchinsert response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully inserted conversion for mobile device ID {0}.", - conversionMobileId); - } else { - Console.WriteLine("Error(s) inserting conversion for mobile device ID {0}:", - conversionMobileId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.5/Conversions/InsertOfflineUserConversion.cs b/dotnet/v3.5/Conversions/InsertOfflineUserConversion.cs deleted file mode 100755 index 88bc7cf..0000000 --- a/dotnet/v3.5/Conversions/InsertOfflineUserConversion.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example inserts an offline conversion attributed to an encrypted user ID. - /// - class InsertOfflineUserConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example inserts an offline conversion attributed to an encrypted user" + - " ID.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new InsertOfflineUserConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long encryptionEntityId = long.Parse(_T("INSERT_ENCRYPTION_ENTITY_TYPE")); - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string conversionUserId = _T("INSERT_CONVERSION_USER_ID_HERE"); - string encryptionEntityType = _T("INSERT_ENCRYPTION_ENTITY_TYPE_HERE"); - string encryptionSource = _T("INSERT_ENCRYPTION_SOURCE_HERE"); - - // Generate a timestamp in milliseconds since Unix epoch. - TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1); - long currentTimeInMilliseconds = (long) timeSpan.TotalMilliseconds; - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Create the conversion. - Conversion conversion = new Conversion(); - conversion.EncryptedUserId = conversionUserId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = currentTimeInMilliseconds.ToString(); - conversion.TimestampMicros = currentTimeInMilliseconds * 1000; - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.EncryptionEntityId = encryptionEntityId; - encryptionInfo.EncryptionEntityType = encryptionEntityType; - encryptionInfo.EncryptionSource = encryptionSource; - - // Insert the conversion. - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.Conversions = new List() { conversion }; - request.EncryptionInfo = encryptionInfo; - - ConversionsBatchInsertResponse response = - service.Conversions.Batchinsert(request, profileId).Execute(); - - // Handle the batchinsert response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully inserted conversion for encrypted user ID {0}.", - conversionUserId); - } else { - Console.WriteLine("Error(s) inserting conversion for encrypted user ID {0}:", - conversionUserId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.5/Conversions/UpdateOfflineMobileConversion.cs b/dotnet/v3.5/Conversions/UpdateOfflineMobileConversion.cs deleted file mode 100755 index 47fdc48..0000000 --- a/dotnet/v3.5/Conversions/UpdateOfflineMobileConversion.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example updates an offline conversion attributed to a mobile device ID. To create a - /// conversion attributed to a mobile device ID, run InsertOfflineMobileConversion.cs. - /// - class UpdateOfflineMobileConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example updates an offline conversion attributed to a mobile device ID. " + - "To create a conversion attributed to a mobile device ID, run " + - "InsertOfflineMobileConversion.cs\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new UpdateOfflineMobileConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Values that identify the existing conversion. - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long conversionTimestamp = long.Parse(_T("INSERT_CONVERSION_TIMESTAMP_HERE")); - string conversionOrdinal = _T("INSERT_CONVERSION_ORDINAL_VALUE_HERE"); - string conversionMobileId = _T("INSERT_CONVERSION_MOBILE_ID_HERE"); - - // Values to update for the specified conversion. - long newQuantity = long.Parse(_T("INSERT_NEW_CONVERSION_QUANTITY_HERE")); - long newValue = long.Parse(_T("INSERT_NEW_CONVERSION_VALUE_HERE")); - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Construct the conversion object with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.MobileDeviceId = conversionMobileId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = conversionOrdinal; - conversion.TimestampMicros = conversionTimestamp; - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.Quantity = newQuantity; - conversion.Value = newValue; - - // Update the conversion. - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.Conversions = new List() { conversion }; - - ConversionsBatchUpdateResponse response = - service.Conversions.Batchupdate(request, profileId).Execute(); - - // Handle the batchupdate response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully updated conversion for mobile device ID {0}.", - conversionMobileId); - } else { - Console.WriteLine("Error(s) updating conversion for mobile device ID {0}:", - conversionMobileId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.5/Conversions/UpdateOfflineUserConversion.cs b/dotnet/v3.5/Conversions/UpdateOfflineUserConversion.cs deleted file mode 100755 index 151d253..0000000 --- a/dotnet/v3.5/Conversions/UpdateOfflineUserConversion.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example updates an offline conversion attributed to an encrypted user ID. To create a - /// conversion attributed to an excrypted user ID, run InsertOfflineUserConversion.cs. - /// - class UpdateOfflineUserConversion : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example updates an offline conversion attributed to an encrypted user ID. " + - "To create a conversion attributed to an encrypted user ID, run " + - "InsertOfflineUserConversion.cs\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new UpdateOfflineUserConversion(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Value that specify how the existing conversion is encrypted. - long encryptionEntityId = long.Parse(_T("INSERT_ENCRYPTION_ENTITY_TYPE")); - string encryptionEntityType = _T("INSERT_ENCRYPTION_ENTITY_TYPE_HERE"); - string encryptionSource = _T("INSERT_ENCRYPTION_SOURCE_HERE"); - - // Values that identify the existing conversion. - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long conversionTimestamp = long.Parse(_T("INSERT_CONVERSION_TIMESTAMP_HERE")); - string conversionOrdinal = _T("INSERT_CONVERSION_ORDINAL_VALUE_HERE"); - string conversionUserId = _T("INSERT_CONVERSION_USER_ID_HERE"); - - // Values to update for the specified conversion. - long newQuantity = long.Parse(_T("INSERT_NEW_CONVERSION_QUANTITY_HERE")); - long newValue = long.Parse(_T("INSERT_NEW_CONVERSION_VALUE_HERE")); - - // Find the Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = - service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); - long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; - - // Construct the conversion object with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.EncryptedUserId = conversionUserId; - conversion.FloodlightActivityId = floodlightActivityId; - conversion.FloodlightConfigurationId = floodlightConfigurationId; - conversion.Ordinal = conversionOrdinal; - conversion.TimestampMicros = conversionTimestamp; - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.Quantity = newQuantity; - conversion.Value = newValue; - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.EncryptionEntityId = encryptionEntityId; - encryptionInfo.EncryptionEntityType = encryptionEntityType; - encryptionInfo.EncryptionSource = encryptionSource; - - // Insert the conversion. - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.Conversions = new List() { conversion }; - request.EncryptionInfo = encryptionInfo; - - ConversionsBatchUpdateResponse response = - service.Conversions.Batchupdate(request, profileId).Execute(); - - // Handle the batchinsert response. - if (!response.HasFailures.Value) { - Console.WriteLine("Successfully updated conversion for encrypted user ID {0}.", - conversionUserId); - } else { - Console.WriteLine("Error(s) updating conversion for encrypted user ID {0}:", - conversionUserId); - - ConversionStatus status = response.Status[0]; - foreach(ConversionError error in status.Errors) { - Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); - } - } - } - } -} diff --git a/dotnet/v3.5/Creatives/Assets/CreativeAssetUtils.cs b/dotnet/v3.5/Creatives/Assets/CreativeAssetUtils.cs deleted file mode 100755 index 1b09727..0000000 --- a/dotnet/v3.5/Creatives/Assets/CreativeAssetUtils.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.IO; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; -using Google.Apis.Upload; - -namespace DfaReporting.Samples { - class CreativeAssetUtils { - private static DfareportingService Service; - private static long ProfileId; - private static long AdvertiserId; - - public CreativeAssetUtils(DfareportingService service, long profileId, long advertiserId) { - AdvertiserId = advertiserId; - ProfileId = profileId; - Service = service; - } - - /// - /// Uploads a creative asset and associates it with the specified advertiser. - /// - /// The path to the asset file to be uploaded - /// The CreativeAssetId type of the asset - /// - /// A CreativeAssetMetadata object populated with the name of the asset after insert. - /// - public CreativeAssetMetadata uploadAsset(String assetFile, String assetType) { - // Prepare an input stream. - FileStream assetContent = new FileStream(assetFile, FileMode.Open, FileAccess.Read); - - // Create the creative asset ID and Metadata. - CreativeAssetId assetId = new CreativeAssetId(); - assetId.Name = Path.GetFileName(assetFile); - assetId.Type = assetType; - - CreativeAssetMetadata metaData = new CreativeAssetMetadata(); - metaData.AssetIdentifier = assetId; - - // Insert the creative. - String mimeType = determineMimeType(assetFile, assetType); - CreativeAssetsResource.InsertMediaUpload request = - Service.CreativeAssets.Insert(metaData, ProfileId, AdvertiserId, assetContent, mimeType); - - IUploadProgress progress = request.Upload(); - if (UploadStatus.Failed.Equals(progress.Status)) { - throw progress.Exception; - } - - // Display the new asset name. - Console.WriteLine("Creative asset was saved with name \"{0}\".", - request.ResponseBody.AssetIdentifier.Name); - return request.ResponseBody; - } - - private String determineMimeType(String assetFile, String assetType) { - switch (assetType) { - case "IMAGE": - case "HTML_IMAGE": - return "image/" + Path.GetExtension(assetFile); - case "VIDEO": - return "video/" + Path.GetExtension(assetFile); - default: - return "application/octet-stream"; - } - } - } -} diff --git a/dotnet/v3.5/Creatives/AssignCreativeToCampaign.cs b/dotnet/v3.5/Creatives/AssignCreativeToCampaign.cs deleted file mode 100755 index cd86935..0000000 --- a/dotnet/v3.5/Creatives/AssignCreativeToCampaign.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example assigns a given creative to a given campaign. Note that both - /// the creative and campaign must be associated with the same advertiser. - /// - class AssignCreativeToCampaign : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example assigns a given creative to a given campaign." + - " Note that both the creative and campaign must be associated with" + - " the same advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new AssignCreativeToCampaign(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long creativeId = long.Parse(_T("INSERT_CREATIVE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Create the campaign creative association structure. - CampaignCreativeAssociation association = new CampaignCreativeAssociation(); - association.CreativeId = creativeId; - - // Insert the association. - CampaignCreativeAssociation result = - service.CampaignCreativeAssociations.Insert(association, profileId, campaignId).Execute(); - - // Display a success message. - Console.WriteLine("Creative with ID {0} is now associated with campaign {1}.", - result.CreativeId, campaignId); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateCreativeField.cs b/dotnet/v3.5/Creatives/CreateCreativeField.cs deleted file mode 100755 index 3722f6c..0000000 --- a/dotnet/v3.5/Creatives/CreateCreativeField.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a creative field associated with a given advertiser. - /// To get an advertiser ID, run GetAdvertisers.cs. - /// - class CreateCreativeField : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a creative field associated with a" + - " given advertiser. To get an advertiser ID, run" + - " GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCreativeField(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string creativeFieldName = _T("INSERT_CREATIVE_FIELD_NAME_HERE"); - - // Create the creative field. - CreativeField creativeField = new CreativeField(); - creativeField.Name = creativeFieldName; - creativeField.AdvertiserId = advertiserId; - - // Insert the creative field. - CreativeField result = - service.CreativeFields.Insert(creativeField, profileId).Execute(); - - // Display the new creative field ID. - Console.WriteLine("Creative field with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateCreativeFieldValue.cs b/dotnet/v3.5/Creatives/CreateCreativeFieldValue.cs deleted file mode 100755 index b4e2990..0000000 --- a/dotnet/v3.5/Creatives/CreateCreativeFieldValue.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a creative field value associated with a given - /// creative field. To get the creative field ID, run GetCreativeFields.java. - /// - class CreateCreativeFieldValue : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a creative field value associated with" + - " a given creative field. To get the creative field ID, run" + - " GetCreativeFields.java.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCreativeFieldValue(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long creativeFieldId = long.Parse(_T("INSERT_CREATIVE_FIELD_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string creativeFieldValueName = _T("INSERT_CREATIVE_FIELD_VALUE_NAME_HERE"); - - // Create the creative field value. - CreativeFieldValue creativeFieldValue = new CreativeFieldValue(); - creativeFieldValue.Value = creativeFieldValueName; - - // Insert the creative field value. - CreativeFieldValue result = service.CreativeFieldValues - .Insert(creativeFieldValue, profileId, creativeFieldId).Execute(); - - // Display the new creative field value ID. - Console.WriteLine("Creative field value with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateCreativeGroup.cs b/dotnet/v3.5/Creatives/CreateCreativeGroup.cs deleted file mode 100755 index 9ecc32f..0000000 --- a/dotnet/v3.5/Creatives/CreateCreativeGroup.cs +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a creative group associated with a given advertiser. - /// To get an advertiser ID, run getAdvertisers.cs. Valid group numbers are - /// limited to 1 or 2. - /// - class CreateCreativeGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a creative group associated with a given" + - " advertiser. To get an advertiser ID, run getAdvertisers.cs. Valid" + - " group numbers are limited to 1 or 2.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateCreativeGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - int groupNumber = int.Parse(_T("INSERT_GROUP_NUMBER_HERE")); - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string creativeGroupName = _T("INSERT_CREATIVE_GROUP_NAME_HERE"); - - // Create the creative group. - CreativeGroup creativeGroup = new CreativeGroup(); - creativeGroup.Name = creativeGroupName; - creativeGroup.GroupNumber = groupNumber; - creativeGroup.AdvertiserId = advertiserId; - - // Insert the creative group. - CreativeGroup result = - service.CreativeGroups.Insert(creativeGroup, profileId).Execute(); - - // Display the new creative group ID. - Console.WriteLine("Creative group with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateDisplayImageGalleryCreative.cs b/dotnet/v3.5/Creatives/CreateDisplayImageGalleryCreative.cs deleted file mode 100755 index 84770e6..0000000 --- a/dotnet/v3.5/Creatives/CreateDisplayImageGalleryCreative.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates a display image - /// gallery creative associated with a given advertiser. To get a size ID, - /// run GetSize.cs. - /// - class CreateDisplayImageGalleryCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates a display" + - " image gallery creative associated with a given advertiser. To" + - " get a size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateDisplayImageGalleryCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string pathToImageAssetFile = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - string pathToImageAsset2File = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.AutoAdvanceImages = true; - creative.Name = "Test display image gallery creative"; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY_IMAGE_GALLERY"; - - // Upload the first image asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId imageAsset1Id = - assetUtils.uploadAsset(pathToImageAssetFile, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset1 = new CreativeAsset(); - imageAsset1.AssetIdentifier = imageAsset1Id; - imageAsset1.Role = "PRIMARY"; - - // Upload the second image asset. - CreativeAssetId imageAsset2Id = - assetUtils.uploadAsset(pathToImageAsset2File, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset2 = new CreativeAsset(); - imageAsset2.AssetIdentifier = imageAsset2Id; - imageAsset2.Role = "PRIMARY"; - - // Add the creative assets. - creative.CreativeAssets = new List() { imageAsset1, imageAsset2 }; - - // Create a click tag for the first image asset. - ClickTag clickTag1 = new ClickTag(); - clickTag1.Name = imageAsset1Id.Name; - clickTag1.EventName = imageAsset1Id.Name; - - // Create a click tag for the second image asset. - ClickTag clickTag2 = new ClickTag(); - clickTag2.Name = imageAsset2Id.Name; - clickTag2.EventName = imageAsset2Id.Name; - - // Add the click tags. - creative.ClickTags = new List() { clickTag1, clickTag2 }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Display image gallery creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateDisplayRedirectCreative.cs b/dotnet/v3.5/Creatives/CreateDisplayRedirectCreative.cs deleted file mode 100755 index ee08aaf..0000000 --- a/dotnet/v3.5/Creatives/CreateDisplayRedirectCreative.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a display redirect creative associated with a given - /// advertiser. To get a size ID, run GetSize.cs. - /// - class CreateDisplayRedirectCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a display redirect creative associated" + - " with a given advertiser. To get a size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateDisplayRedirectCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string imageUrl = _T("INSERT_IMAGE_URL_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test display redirect creative"; - creative.RedirectUrl = imageUrl; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY_REDIRECT"; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Display redirect creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateHTML5DisplayCreative.cs b/dotnet/v3.5/Creatives/CreateHTML5DisplayCreative.cs deleted file mode 100755 index ae84481..0000000 --- a/dotnet/v3.5/Creatives/CreateHTML5DisplayCreative.cs +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an HTML5 display - /// creative associated with a given advertiser. To get a size ID, run - /// GetSize.cs. - /// - class CreateHTML5DisplayCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an HTML5" + - " display creative associated with a given advertiser. To get a" + - " size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateHTML5DisplayCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string pathToHtml5AssetFile = _T("INSERT_PATH_TO_HTML5_ASSET_FILE_HERE"); - string pathToImageAssetFile = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(service, profileId, advertiserId); - - // Create the creative structure. - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test HTML5 display creative"; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY"; - - // Upload the HTML5 asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId html5AssetId = - assetUtils.uploadAsset(pathToHtml5AssetFile, "HTML").AssetIdentifier; - - CreativeAsset html5Asset = new CreativeAsset(); - html5Asset.AssetIdentifier = html5AssetId; - html5Asset.Role = "PRIMARY"; - - // Upload the backup image asset. - CreativeAssetId imageAssetId = - assetUtils.uploadAsset(pathToImageAssetFile, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset = new CreativeAsset(); - imageAsset.AssetIdentifier = imageAssetId; - imageAsset.Role = "BACKUP_IMAGE"; - - // Add the creative assets. - creative.CreativeAssets = new List() { html5Asset, imageAsset }; - - // Configure the bacup image. - creative.BackupImageClickThroughUrl = new CreativeClickThroughUrl() { - LandingPageId = defaultLandingPage.Id - }; - creative.BackupImageReportingLabel = "backup"; - creative.BackupImageTargetWindow = new TargetWindow() { TargetWindowOption = "NEW_WINDOW" }; - - // Add a click tag. - ClickTag clickTag = new ClickTag(); - clickTag.Name = "clickTag"; - clickTag.EventName = "exit"; - clickTag.ClickThroughUrl = new CreativeClickThroughUrl() { - LandingPageId = defaultLandingPage.Id - }; - creative.ClickTags = new List() { clickTag }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("HTML5 display creative with ID {0} was created.", result.Id); - } - - private LandingPage getAdvertiserLandingPage(DfareportingService service, long profileId, - long advertiserId) { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesResource.ListRequest listRequest = - service.AdvertiserLandingPages.List(profileId); - listRequest.AdvertiserIds = new List() { advertiserId.ToString() }; - listRequest.MaxResults = 1; - - AdvertiserLandingPagesListResponse landingPages = listRequest.Execute(); - - if (landingPages.LandingPages == null || landingPages.LandingPages.Count == 0) { - throw new InvalidOperationException( - String.Format("No landing pages found for advertiser with ID {0}.", advertiserId)); - } - - return landingPages.LandingPages[0]; - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateImageDisplayCreative.cs b/dotnet/v3.5/Creatives/CreateImageDisplayCreative.cs deleted file mode 100755 index 6f46adc..0000000 --- a/dotnet/v3.5/Creatives/CreateImageDisplayCreative.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.IO; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an image display - /// creative associated with a given advertiser. To get a size ID, run - /// GetSize.cs. - /// - class CreateImageDisplayCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an image display" + - " creative associated with a given advertiser. To get a size ID," + - " run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateImageDisplayCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string pathToImageAssetFile = _T("INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test image display creative"; - creative.Size = new Size() { Id = sizeId }; - creative.Type = "DISPLAY"; - - // Upload the image asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId imageAssetId = - assetUtils.uploadAsset(pathToImageAssetFile, "HTML_IMAGE").AssetIdentifier; - - CreativeAsset imageAsset = new CreativeAsset(); - imageAsset.AssetIdentifier = imageAssetId; - imageAsset.Role = "PRIMARY"; - - // Add the creative assets. - creative.CreativeAssets = new List() { imageAsset }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Image display creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateInstreamAudioCreative.cs b/dotnet/v3.5/Creatives/CreateInstreamAudioCreative.cs deleted file mode 100755 index e338204..0000000 --- a/dotnet/v3.5/Creatives/CreateInstreamAudioCreative.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an in-stream audio - /// creative associated with a given advertiser. - /// - class CreateInstreamAudioCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an" + - " in-stream audio creative associated with a given advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateInstreamAudioCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string audioAssetName = _T("INSERT_AUDIO_ASSET_NAME_HERE"); - string pathToAudioAssetFile = _T("INSERT_PATH_TO_AUDIO_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test in-stream audio creative"; - creative.Type = "INSTREAM_AUDIO"; - - // Upload the audio asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId audioAssetId = - assetUtils.uploadAsset(pathToAudioAssetFile, "AUDIO").AssetIdentifier; - - CreativeAsset audioAsset = new CreativeAsset(); - audioAsset.AssetIdentifier = audioAssetId; - audioAsset.Role = "PARENT_AUDIO"; - - // Add the creative assets. - creative.CreativeAssets = new List() { audioAsset }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("In-stream audio creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateInstreamVideoCreative.cs b/dotnet/v3.5/Creatives/CreateInstreamVideoCreative.cs deleted file mode 100755 index 5f8004a..0000000 --- a/dotnet/v3.5/Creatives/CreateInstreamVideoCreative.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads creative assets and creates an in-stream video - /// creative associated with a given advertiser. - /// - class CreateInstreamVideoCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads creative assets and creates an" + - " in-stream video creative associated with a given advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateInstreamVideoCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string videoAssetName = _T("INSERT_VIDEO_ASSET_NAME_HERE"); - string pathToVideoAssetFile = _T("INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test in-stream video creative"; - creative.Type = "INSTREAM_VIDEO"; - - // Upload the video asset. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId); - CreativeAssetId videoAssetId = - assetUtils.uploadAsset(pathToVideoAssetFile, "VIDEO").AssetIdentifier; - - CreativeAsset videoAsset = new CreativeAsset(); - videoAsset.AssetIdentifier = videoAssetId; - videoAsset.Role = "PARENT_VIDEO"; - - // Add the creative assets. - creative.CreativeAssets = new List() { videoAsset }; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("In-stream video creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/CreateTrackingCreative.cs b/dotnet/v3.5/Creatives/CreateTrackingCreative.cs deleted file mode 100755 index 8b6a38f..0000000 --- a/dotnet/v3.5/Creatives/CreateTrackingCreative.cs +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a tracking creative associated with a given - /// advertiser. - /// - class CreateTrackingCreative : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a tracking creative associated with a" + - " given advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateTrackingCreative(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - Creative creative = new Creative(); - creative.AdvertiserId = advertiserId; - creative.Name = "Test tracking creative"; - creative.Type = "TRACKING_TEXT"; - - Creative result = service.Creatives.Insert(creative, profileId).Execute(); - - // Display the new creative ID. - Console.WriteLine("Tracking creative with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Creatives/GetCreativeFieldValues.cs b/dotnet/v3.5/Creatives/GetCreativeFieldValues.cs deleted file mode 100755 index 0f7bdac..0000000 --- a/dotnet/v3.5/Creatives/GetCreativeFieldValues.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example retrieves available creative field values for a given string - /// and displays the names and IDs. - /// - class GetCreativeFieldValues : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example retrieves available creative field values for a" + - " given string and displays the names and IDs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreativeFieldValues(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long creativeFieldId = long.Parse(_T("ENTER_CREATIVE_FIELD_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - CreativeFieldValuesListResponse values; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - CreativeFieldValuesResource.ListRequest request = - service.CreativeFieldValues.List(profileId, creativeFieldId); - request.PageToken = nextPageToken; - values = request.Execute(); - - foreach (CreativeFieldValue value in values.CreativeFieldValues) { - Console.WriteLine("Found creative field value with ID {0} and value \"{1}\".", - value.Id, value.Value); - } - - // Update the next page token. - nextPageToken = values.NextPageToken; - } while (values.CreativeFieldValues.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Creatives/GetCreativeFields.cs b/dotnet/v3.5/Creatives/GetCreativeFields.cs deleted file mode 100755 index 6ddfcfd..0000000 --- a/dotnet/v3.5/Creatives/GetCreativeFields.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all creative fields. - /// - class GetCreativeFields : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all creative fields.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreativeFields(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - CreativeFieldsListResponse fields; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - CreativeFieldsResource.ListRequest request = service.CreativeFields.List(profileId); - request.PageToken = nextPageToken; - fields = request.Execute(); - - foreach (CreativeField field in fields.CreativeFields) { - Console.WriteLine("Found creative field with ID {0} and name \"{1}\".", - field.Id, field.Name); - } - - // Update the next page token. - nextPageToken = fields.NextPageToken; - } while (fields.CreativeFields.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Creatives/GetCreativeGroups.cs b/dotnet/v3.5/Creatives/GetCreativeGroups.cs deleted file mode 100755 index dee8410..0000000 --- a/dotnet/v3.5/Creatives/GetCreativeGroups.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all creative groups. - /// - class GetCreativeGroups : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all creative groups.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreativeGroups(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - CreativeGroupsListResponse groups; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - CreativeGroupsResource.ListRequest request = service.CreativeGroups.List(profileId); - request.PageToken = nextPageToken; - groups = request.Execute(); - - foreach (CreativeGroup group in groups.CreativeGroups) { - Console.WriteLine("Found creative group with ID {0} and value \"{1}\".", - group.Id, group.Name); - } - - // Update the next page token. - nextPageToken = groups.NextPageToken; - } while (groups.CreativeGroups.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Creatives/GetCreatives.cs b/dotnet/v3.5/Creatives/GetCreatives.cs deleted file mode 100755 index ec4721a..0000000 --- a/dotnet/v3.5/Creatives/GetCreatives.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all existing active creatives for a given advertiser. - /// To get an advertiser ID, run GetAdvertisers.cs. - /// - class GetCreatives : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all existing active creatives for a given" + - " advertiser. To get an advertiser ID, run GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCreatives(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("ENTER_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,creatives(id,name,type)"; - - CreativesListResponse creatives; - String nextPageToken = null; - - do { - // Create and execute the campaigns list request. - CreativesResource.ListRequest request = service.Creatives.List(profileId); - request.Active = true; - request.AdvertiserId = advertiserId; - request.Fields = fields; - request.PageToken = nextPageToken; - creatives = request.Execute(); - - foreach (Creative creative in creatives.Creatives) { - Console.WriteLine("Found {0} creative with ID {1} and name \"{2}\".", - creative.Type, creative.Id, creative.Name); - } - - // Update the next page token. - nextPageToken = creatives.NextPageToken; - } while (creatives.Creatives.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/DfaReporting.Samples.csproj b/dotnet/v3.5/DfaReporting.Samples.csproj deleted file mode 100644 index f91f23d..0000000 --- a/dotnet/v3.5/DfaReporting.Samples.csproj +++ /dev/null @@ -1,176 +0,0 @@ - - - - - Debug - AnyCPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC} - Exe - Properties - DfaReporting.Samples - DfaReporting.Samples - v4.5 - 512 - .\ - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - DfaReporting.Samples.Program - - - - packages\Google.Apis.1.51.0\lib\net45\Google.Apis.dll - True - - - packages\Google.Apis.Auth.1.51.0\lib\net45\Google.Apis.Auth.dll - True - - - packages\Google.Apis.Auth.1.51.0\lib\net45\Google.Apis.Auth.PlatformServices.dll - True - - - packages\Google.Apis.Core.1.51.0\lib\net45\Google.Apis.Core.dll - True - - - packages\Google.Apis.Dfareporting.v3_5.1.51.0.2332\lib\net45\Google.Apis.Dfareporting.v3_5.dll - True - - - packages\Google.Apis.1.51.0\lib\net45\Google.Apis.PlatformServices.dll - True - - - packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Always - - - - - - diff --git a/dotnet/v3.5/DfaReporting.Samples.sln b/dotnet/v3.5/DfaReporting.Samples.sln deleted file mode 100755 index cc59936..0000000 --- a/dotnet/v3.5/DfaReporting.Samples.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DfaReporting.Samples", "DfaReporting.Samples.csproj", "{2425B70F-5543-4E51-B8D0-D7A9D04259BC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2425B70F-5543-4E51-B8D0-D7A9D04259BC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/dotnet/v3.5/DfaReportingDateConverterUtil.cs b/dotnet/v3.5/DfaReportingDateConverterUtil.cs deleted file mode 100755 index 9377029..0000000 --- a/dotnet/v3.5/DfaReportingDateConverterUtil.cs +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; - -namespace DfaReporting.Samples { - /// - /// This simple utility converts DateTime objects to the string - /// formats that the DCM/DFA Reporting and Trafficking API expects dates to - /// be in. - /// - internal static class DfaReportingDateConverterUtil { - private const string DateFormat = "yyyy-MM-dd"; - private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.FFFZ"; - - /// - /// Takes a DateTime object and converts it to the proper date-only - /// string format for the DCM/DFA Reporting and Trafficking API. - /// - /// The date to be converted. - /// The given date in the proper format. - public static string convertToDateString(DateTime date) { - return date.ToString(DateFormat); - } - - /// - /// Takes a DateTime object and converts it to the proper datetime - /// string format for the DCM/DFA Reporting and Trafficking API. - /// - /// The date to be converted. - /// The given date in the proper format. - public static string convertToDateTimeString(DateTime date) { - return date.ToString(DateTimeFormat); - } - } -} \ No newline at end of file diff --git a/dotnet/v3.5/DfaReportingFactory.cs b/dotnet/v3.5/DfaReportingFactory.cs deleted file mode 100755 index c7a0fd5..0000000 --- a/dotnet/v3.5/DfaReportingFactory.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Threading; -using Google.Apis.Auth.OAuth2; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Services; -using Google.Apis.Util.Store; - -namespace DfaReporting.Samples { - /// - /// Factory for generating DFA Reporting and Trafficking API service objects. - /// - class DfaReportingFactory { - /// - /// The scopes used to make reporting and trafficking requests. - /// - private static readonly IEnumerable scopes = new[] { - DfareportingService.Scope.Dfareporting, - DfareportingService.Scope.Dfatrafficking, - DfareportingService.Scope.Ddmconversions - }; - - /// - /// Authorizes the application to access users' protected data. - /// - private static ICredential Authorize() { - // Load application default credentials if they're available. - ICredential credential = LoadApplicationDefaultCredentials(); - - // Otherwise, load credentials from the provided client secrets file. - if (credential == null) { - credential = LoadUserCredentials("client_secrets.json", - new FileDataStore("DfaReporting.Samples")); - } - - return credential; - } - - /// - /// Attempts to load the application default credentials - /// - /// The application default credentials, or null if none were found. - private static ICredential LoadApplicationDefaultCredentials() { - try { - GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result; - return credential.CreateScoped(scopes); - } catch (Exception) { - // No application default credentials, continue to try other options. - } - - return null; - } - - /// - /// Attempts to load user credentials from the provided client secrets file and persists data to - /// the provided data store. - /// - /// The user credentials. - /// Path to the file containing client secrets. - /// The data store to use for caching credential information. - private static ICredential LoadUserCredentials(String clientSecretsFile, IDataStore dataStore) { - using (var stream = new System.IO.FileStream(clientSecretsFile, System.IO.FileMode.Open, - System.IO.FileAccess.Read)) { - return GoogleWebAuthorizationBroker.AuthorizeAsync( - GoogleClientSecrets.Load(stream).Secrets, - scopes, - "dfa-user", CancellationToken.None, - dataStore).Result; - } - } - - /// - /// Initializes a DfaReportingService instance. - /// - /// An initialized DfaReportingService object. - public static DfareportingService getInstance() { - ICredential credential = Authorize(); - - // Create and return the service. - return new DfareportingService(new BaseClientService.Initializer { - HttpClientInitializer = credential, - ApplicationName = "DFA/DCM Reporting and Trafficking API Samples" - }); - } - } -} diff --git a/dotnet/v3.5/Floodlight/CreateFloodlightActivity.cs b/dotnet/v3.5/Floodlight/CreateFloodlightActivity.cs deleted file mode 100755 index 430cedf..0000000 --- a/dotnet/v3.5/Floodlight/CreateFloodlightActivity.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a floodlight activity in a given activity group. To - /// create an activity group, run CreateFloodlightActivityGroup.cs. - /// - class CreateFloodlightActivity : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a floodlight activity in a given" + - " activity group. To create an activity group, run" + - " CreateFloodlightActivityGroup.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateFloodlightActivity(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long activityGroupId = long.Parse(_T("INSERT_ACTIVITY_GROUP_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String activityName = _T("INSERT_ACTIVITY_NAME_HERE"); - String url = _T("INSERT_EXPECTED_URL_HERE"); - - // Set floodlight activity structure. - FloodlightActivity activity = new FloodlightActivity(); - activity.CountingMethod = "STANDARD_COUNTING"; - activity.Name = activityName; - activity.FloodlightActivityGroupId = activityGroupId; - activity.FloodlightTagType = "GLOBAL_SITE_TAG"; - activity.ExpectedUrl = url; - - // Create the floodlight tag activity. - FloodlightActivity result = - service.FloodlightActivities.Insert(activity, profileId).Execute(); - - // Display new floodlight activity ID. - if (result != null) { - Console.WriteLine("Floodlight activity with ID {0} was created.", result.Id); - } - } - } -} diff --git a/dotnet/v3.5/Floodlight/CreateFloodlightActivityGroup.cs b/dotnet/v3.5/Floodlight/CreateFloodlightActivityGroup.cs deleted file mode 100755 index 1ec43d5..0000000 --- a/dotnet/v3.5/Floodlight/CreateFloodlightActivityGroup.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a new activity group for a given floodlight - /// configuration. To get a floodlight tag configuration ID, run - /// GetAdvertisers.cs. - /// - class CreateFloodlightActivityGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a new activity group for a given" + - " floodlight configuration. To get a floodlight tag configuration" + - " ID, run GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateFloodlightActivityGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long floodlightConfigurationId = - long.Parse(_T("INSERT_FLOODLIGHT_CONFIGURATION_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String groupName = _T("INSERT_GROUP_NAME_HERE"); - - // Create the floodlight activity group. - FloodlightActivityGroup floodlightActivityGroup = new FloodlightActivityGroup(); - floodlightActivityGroup.Name = groupName; - floodlightActivityGroup.FloodlightConfigurationId = floodlightConfigurationId; - floodlightActivityGroup.Type = "COUNTER"; - - // Insert the activity group. - FloodlightActivityGroup result = - service.FloodlightActivityGroups.Insert(floodlightActivityGroup, profileId).Execute(); - - // Display the new activity group ID. - if (result != null) { - Console.WriteLine("Activity group with ID {0} was created.", result.Id); - } - } - } -} diff --git a/dotnet/v3.5/Floodlight/DownloadFloodlightTags.cs b/dotnet/v3.5/Floodlight/DownloadFloodlightTags.cs deleted file mode 100755 index c7b5e02..0000000 --- a/dotnet/v3.5/Floodlight/DownloadFloodlightTags.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example downloads activity tags for a given floodlight activity. - /// - class DownloadFloodlightTags : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example downloads activity tags for a given floodlight" + - " activity.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DownloadFloodlightTags(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long activityId = long.Parse(_T("ENTER_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Generate the floodlight activity tag. - FloodlightActivitiesResource.GeneratetagRequest request = - service.FloodlightActivities.Generatetag(profileId); - request.FloodlightActivityId = activityId; - - FloodlightActivitiesGenerateTagResponse response = request.Execute(); - - if (response.GlobalSiteTagGlobalSnippet != null) { - // This is a global site tag, display both the global snippet and event snippet. - Console.WriteLine("Global site tag global snippet:\n\n{0}", - response.GlobalSiteTagGlobalSnippet); - Console.WriteLine("\n\nGlobal site tag event snippet:\n\n{0}", - response.FloodlightActivityTag); - } else { - // This is an image or iframe tag. - Console.WriteLine("Floodlight activity tag:\n\n{0}", response.FloodlightActivityTag); - } - } - } -} diff --git a/dotnet/v3.5/Floodlight/GetFloodlightActivities.cs b/dotnet/v3.5/Floodlight/GetFloodlightActivities.cs deleted file mode 100755 index b5b8b80..0000000 --- a/dotnet/v3.5/Floodlight/GetFloodlightActivities.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays floodlight activities for a given advertiser. To - /// create an advertiser, run CreateAdvertiser.cs. - /// - class GetFloodlightActivities : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays floodlight activities for a given" + - " advertiser. To create an advertiser, run CreateAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetFloodlightActivities(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,floodlightActivities(id,name)"; - - FloodlightActivitiesListResponse activities; - String nextPageToken = null; - - do { - // Create and execute the floodlight activities list request. - FloodlightActivitiesResource.ListRequest request = - service.FloodlightActivities.List(profileId); - request.AdvertiserId = advertiserId; - request.Fields = fields; - request.PageToken = nextPageToken; - activities = request.Execute(); - - foreach (FloodlightActivity activity in activities.FloodlightActivities) { - Console.WriteLine("Floodlight activity with ID {0} and name \"{1}\"" + - " was found.", activity.Id, activity.Name); - } - - // Update the next page token. - nextPageToken = activities.NextPageToken; - } while (activities.FloodlightActivities.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Floodlight/GetFloodlightActivityGroups.cs b/dotnet/v3.5/Floodlight/GetFloodlightActivityGroups.cs deleted file mode 100755 index e4ce2d5..0000000 --- a/dotnet/v3.5/Floodlight/GetFloodlightActivityGroups.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays floodlight activity groups for a given advertiser. - /// To create an advertiser, run CreateAdvertiser.cs. - /// - class GetFloodlightActivityGroups : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays floodlight activity groups for a given" + - " advertiser. To create an advertiser, run CreateAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetFloodlightActivityGroups(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "floodlightActivityGroups(id,name)"; - - // Create and execute the floodlight activity groups list request. - FloodlightActivityGroupsResource.ListRequest request = - service.FloodlightActivityGroups.List(profileId); - request.AdvertiserId = advertiserId; - request.Fields = fields; - FloodlightActivityGroupsListResponse groups = request.Execute(); - - foreach (FloodlightActivityGroup group in groups.FloodlightActivityGroups) { - Console.WriteLine("Floodlight activity group with ID {0} and name" + - " \"{1}\" was found.", group.Id, group.Name); - } - } - } -} diff --git a/dotnet/v3.5/Misc/GetChangeLogsForAdvertiser.cs b/dotnet/v3.5/Misc/GetChangeLogsForAdvertiser.cs deleted file mode 100755 index cf4b0ab..0000000 --- a/dotnet/v3.5/Misc/GetChangeLogsForAdvertiser.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the change logs of a specified advertiser object. - /// A similar pattern can be applied to get change logs for many other object - /// types. - /// - class GetChangeLogsForAdvertiser : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the change logs of a specified" + - " advertiser object. A similar pattern can be applied to get" + - " change logs for many other object types.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetChangeLogsForAdvertiser(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,changeLogs(action,fieldName,oldValue,newValue)"; - - ChangeLogsListResponse changeLogs; - String nextPageToken = null; - - do { - // Create and execute the change logs list request - ChangeLogsResource.ListRequest request = service.ChangeLogs.List(profileId); - request.ObjectIds = advertiserId.ToString(); - request.ObjectType = ChangeLogsResource.ListRequest.ObjectTypeEnum.OBJECTADVERTISER; - request.Fields = fields; - request.PageToken = nextPageToken; - changeLogs = request.Execute(); - - foreach (ChangeLog changeLog in changeLogs.ChangeLogs) { - Console.WriteLine("{0}: Field \"{1}\" from \"{2}\" to \"{3}\".", - changeLog.Action, changeLog.FieldName, changeLog.OldValue, - changeLog.NewValue); - } - - // Update the next page token. - nextPageToken = changeLogs.NextPageToken; - } while (changeLogs.ChangeLogs.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Misc/GetSites.cs b/dotnet/v3.5/Misc/GetSites.cs deleted file mode 100755 index bf70f39..0000000 --- a/dotnet/v3.5/Misc/GetSites.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example lists all existing sites. - /// - class GetSites : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example lists all existing sites.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSites(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,sites(id,keyName)"; - - SitesListResponse sites; - String nextPageToken = null; - - do { - // Create and execute the sites list request. - SitesResource.ListRequest request = service.Sites.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - sites = request.Execute(); - - foreach (Site site in sites.Sites) { - Console.WriteLine("Found site with ID {0} and key name \"{1}\".", - site.Id, site.KeyName); - } - - // Update the next page token. - nextPageToken = sites.NextPageToken; - } while (sites.Sites.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Misc/GetSize.cs b/dotnet/v3.5/Misc/GetSize.cs deleted file mode 100755 index 9ccf089..0000000 --- a/dotnet/v3.5/Misc/GetSize.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all sizes for a given width and height. - /// - class GetSize : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all sizes for a given width and height.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSize(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - int height = int.Parse(_T("ENTER_HEIGHT_HERE")); - int width = int.Parse(_T("ENTER_WIDTH_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Create and execute the sizes list request. - SizesResource.ListRequest request = service.Sizes.List(profileId); - request.Height = height; - request.Width = width; - SizesListResponse sizes = request.Execute(); - - foreach (Size size in sizes.Sizes) { - Console.WriteLine("Found size with ID {0}.", size.Id); - } - } - } -} diff --git a/dotnet/v3.5/Placements/CreateContentCategory.cs b/dotnet/v3.5/Placements/CreateContentCategory.cs deleted file mode 100755 index 1fa2bac..0000000 --- a/dotnet/v3.5/Placements/CreateContentCategory.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a content category with the given name and - /// description. - /// - class CreateContentCategory : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a content category with the given name" + - " and description.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateContentCategory(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String contentCategoryName = _T("INSERT_CONTENT_CATEGORY_NAME_HERE"); - - // Create the content category. - ContentCategory contentCategory = new ContentCategory(); - contentCategory.Name = contentCategoryName; - - // Insert the content category. - ContentCategory result = - service.ContentCategories.Insert(contentCategory, profileId).Execute(); - - // Display the new content category ID. - Console.WriteLine("Content category with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Placements/CreatePlacement.cs b/dotnet/v3.5/Placements/CreatePlacement.cs deleted file mode 100755 index 7204c36..0000000 --- a/dotnet/v3.5/Placements/CreatePlacement.cs +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a placement in a given campaign. Requires a DFA site - /// ID and ID of the campaign in which the placement will be created. To - /// create a campaign, run CreateCampaign.cs. To get a DFA site ID, run - /// GetSite.cs. To get a size ID, run GetSize.cs. - /// - class CreatePlacement : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a placement in a given campaign." + - " Requires a DFA site ID and ID of the campaign in which the" + - " placement will be created. To create a campaign, run" + - " CreateCampaign.cs. To get a DFA site ID, run GetSite.cs. To get" + - " a size ID, run GetSize.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreatePlacement(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long dfaSiteId = long.Parse(_T("INSERT_SITE_ID_HERE")); - long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string placementName = _T("INSERT_PLACEMENT_NAME_HERE"); - - // Retrieve the campaign. - Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute(); - - // Create the placement. - Placement placement = new Placement(); - placement.Name = placementName; - placement.CampaignId = campaignId; - placement.Compatibility = "DISPLAY"; - placement.PaymentSource = "PLACEMENT_AGENCY_PAID"; - placement.SiteId = dfaSiteId; - placement.TagFormats = new List() { "PLACEMENT_TAG_STANDARD" }; - - // Set the size of the placement. - Size size = new Size(); - size.Id = sizeId; - placement.Size = size; - - // Set the pricing schedule for the placement. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.EndDate = campaign.EndDate; - pricingSchedule.PricingType = "PRICING_TYPE_CPM"; - pricingSchedule.StartDate = campaign.StartDate; - placement.PricingSchedule = pricingSchedule; - - // Insert the placement. - Placement result = service.Placements.Insert(placement, profileId).Execute(); - - // Display the new placement ID. - Console.WriteLine("Placement with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Placements/CreatePlacementGroup.cs b/dotnet/v3.5/Placements/CreatePlacementGroup.cs deleted file mode 100755 index 1749dc9..0000000 --- a/dotnet/v3.5/Placements/CreatePlacementGroup.cs +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a placement group in a given campaign. Requires the - /// DFA site ID and campaign ID in which the placement group will be created - /// into. To create a campaign, run CreateCampaign.cs. To get DFA site ID, - /// run GetSite.cs. - /// - class CreatePlacementGroup : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a placement group in a given campaign." + - " Requires the DFA site ID and campaign ID in which the placement" + - " group will be created into. To create a campaign, run" + - " CreateCampaign.cs. To get DFA site ID, run GetSite.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreatePlacementGroup(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); - long dfaSiteId = long.Parse(_T("INSERT_SITE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string placementGroupName = _T("INSERT_PLACEMENT_GROUP_NAME_HERE"); - - // Retrieve the campaign. - Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute(); - - // Create a pricing schedule. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.EndDate = campaign.EndDate; - pricingSchedule.PricingType = "PRICING_TYPE_CPM"; - pricingSchedule.StartDate = campaign.StartDate; - - // Create the placement group. - PlacementGroup placementGroup = new PlacementGroup(); - placementGroup.CampaignId = campaignId; - placementGroup.Name = placementGroupName; - placementGroup.PlacementGroupType = "PLACEMENT_PACKAGE"; - placementGroup.PricingSchedule = pricingSchedule; - placementGroup.SiteId = dfaSiteId; - - // Insert the placement. - PlacementGroup result = - service.PlacementGroups.Insert(placementGroup, profileId).Execute(); - - // Display the new placement ID. - Console.WriteLine("Placement group with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Placements/CreatePlacementStrategy.cs b/dotnet/v3.5/Placements/CreatePlacementStrategy.cs deleted file mode 100755 index 4db592b..0000000 --- a/dotnet/v3.5/Placements/CreatePlacementStrategy.cs +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a placement strategy with the given name. - /// - class CreatePlacementStrategy : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a placement strategy with the given name.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreatePlacementStrategy(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string placementStrategyName = _T("INSERT_PLACEMENT_STRATEGY_NAME_HERE"); - - // Create the placement strategy. - PlacementStrategy placementStrategy = new PlacementStrategy(); - placementStrategy.Name = placementStrategyName; - - // Insert the placement strategy. - PlacementStrategy result = - service.PlacementStrategies.Insert(placementStrategy, profileId).Execute(); - - // Display the new placement strategy ID. - Console.WriteLine("Placement strategy with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Placements/DownloadPlacementTags.cs b/dotnet/v3.5/Placements/DownloadPlacementTags.cs deleted file mode 100755 index e97be18..0000000 --- a/dotnet/v3.5/Placements/DownloadPlacementTags.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example downloads HTML Tags for a given campaign and placement ID. - /// To create campaigns, run CreateCampaign.cs. To create placements, run - /// CreatePlacement.cs. - /// - class DownloadPlacementTags : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example downloads HTML Tags for a given campaign and" + - " placement ID. To create campaigns, run CreateCampaign.cs. To" + - " create placements, run CreatePlacement.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DownloadPlacementTags(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long campaignId = long.Parse(_T("ENTER_CAMPAIGN_ID_HERE")); - long placementId = long.Parse(_T("ENTER_PLACEMENT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Generate the placement activity tags. - PlacementsResource.GeneratetagsRequest request = - service.Placements.Generatetags(profileId); - request.CampaignId = campaignId; - request.TagFormats = - PlacementsResource.GeneratetagsRequest.TagFormatsEnum.PLACEMENTTAGIFRAMEJAVASCRIPT; - request.PlacementIds = placementId.ToString(); - - PlacementsGenerateTagsResponse response = request.Execute(); - - // Display the placement activity tags. - foreach (PlacementTag tag in response.PlacementTags) { - foreach (TagData tagData in tag.TagDatas) { - Console.WriteLine("{0}:\n", tagData.Format); - - if (tagData.ImpressionTag != null) { - Console.WriteLine(tagData.ImpressionTag); - } - - if (tagData.ClickTag != null) { - Console.WriteLine(tagData.ClickTag); - } - - Console.WriteLine(); - } - } - } - } -} diff --git a/dotnet/v3.5/Placements/GetContentCategories.cs b/dotnet/v3.5/Placements/GetContentCategories.cs deleted file mode 100755 index e065d78..0000000 --- a/dotnet/v3.5/Placements/GetContentCategories.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all available content categories. - /// - class GetContentCategories : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all available content categories.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetContentCategories(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,contentCategories(id,name)"; - - ContentCategoriesListResponse categories; - String nextPageToken = null; - - do { - // Create and execute the content categories list request - ContentCategoriesResource.ListRequest request = - service.ContentCategories.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - categories = request.Execute(); - - foreach (ContentCategory category in categories.ContentCategories) { - Console.WriteLine("Found content category with ID {0} and name \"{1}\".", - category.Id, category.Name); - } - - // Update the next page token - nextPageToken = categories.NextPageToken; - } while (categories.ContentCategories.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Placements/GetPlacementStrategies.cs b/dotnet/v3.5/Placements/GetPlacementStrategies.cs deleted file mode 100755 index 46bbc51..0000000 --- a/dotnet/v3.5/Placements/GetPlacementStrategies.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all available placement strategies. - /// - class GetPlacementStrategies : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all available placement strategies.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetPlacementStrategies(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,placementStrategies(id,name)"; - - PlacementStrategiesListResponse strategies; - String nextPageToken = null; - - do { - // Create and execute the placement strategies list request - PlacementStrategiesResource.ListRequest request = - service.PlacementStrategies.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - strategies = request.Execute(); - - foreach (PlacementStrategy strategy in strategies.PlacementStrategies) { - Console.WriteLine("Found placement strategy with ID {0} and name \"{1}\".", - strategy.Id, strategy.Name); - } - - // Update the next page token - nextPageToken = strategies.NextPageToken; - } while (strategies.PlacementStrategies.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Placements/GetPlacements.cs b/dotnet/v3.5/Placements/GetPlacements.cs deleted file mode 100755 index 6735176..0000000 --- a/dotnet/v3.5/Placements/GetPlacements.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all available placement strategies. - /// - class GetPlacements : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all available placement strategies.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetPlacements(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,placements(campaignId,id,name)"; - - PlacementsListResponse placements; - String nextPageToken = null; - - do { - // Create and execute the placements list request - PlacementsResource.ListRequest request = service.Placements.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - placements = request.Execute(); - - foreach (Placement placement in placements.Placements) { - Console.WriteLine( - "Placement with ID {0} and name \"{1}\" is associated with campaign ID {2}.", - placement.Id, placement.Name, placement.CampaignId); - } - - // Update the next page token - nextPageToken = placements.NextPageToken; - } while (placements.Placements.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Program.cs b/dotnet/v3.5/Program.cs deleted file mode 100755 index 5100650..0000000 --- a/dotnet/v3.5/Program.cs +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using Google.Apis.Dfareporting.v3_5; - -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; - -using SamplePair = System.Collections.Generic.KeyValuePair; - -namespace DfaReporting.Samples { - /// - /// The Main class for this application. - /// - class Program { - /// - /// A map to hold the code examples to be executed. - /// - static List sampleMap = new List(); - - /// - /// A flag to keep track of whether help message was shown earlier. - /// - private static bool helpShown = false; - - static void RegisterSample(string key, SampleBase value) { - sampleMap.Add(new SamplePair(key, value)); - } - /// - /// Static constructor to initialize the sample map. - /// - static Program() { - Type[] types = Assembly.GetExecutingAssembly().GetTypes(); - - foreach (Type type in types) { - if (type.BaseType == typeof(SampleBase)) { - RegisterSample(type.FullName.Replace(typeof(Program).Namespace + ".", ""), - Activator.CreateInstance(type) as SampleBase); - } - } - } - - /// - /// The main method. - /// - /// - public static void Main(string[] args) { - if (args.Length == 0) { - ShowUsage(); - return; - } - - foreach (string cmdArgs in args) { - SamplePair matchingPair = sampleMap.Find(delegate(SamplePair pair) { - return string.Compare(pair.Key, cmdArgs, true) == 0; - }); - - if (matchingPair.Key != null) { - // Initialize the Dfa Reporting service. - DfareportingService service = DfaReportingFactory.getInstance(); - - // Run the sample - RunASample(service, matchingPair.Value); - } else { - ShowUsage(); - } - } - } - - /// - /// Runs a code sample. - /// - /// The user whose credentials should be used for - /// running the sample. - /// The code sample to run. - private static void RunASample(DfareportingService service, SampleBase sample) { - try { - Console.WriteLine(sample.Description); - sample.Run(service); - } catch (Exception ex) { - Console.WriteLine("An exception occurred while running this code example.\n{0} at\n{1}", - ex.Message, ex.StackTrace); - } finally { - Console.WriteLine("Press [Enter] to continue"); - Console.ReadLine(); - } - } - - /// - /// Prints program usage message. - /// - private static void ShowUsage() { - if (helpShown) { - return; - } else { - helpShown = true; - } - string exeName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); - Console.WriteLine("Runs DFA/DCM Reporting and Trafficking API code examples"); - Console.WriteLine("Usage : {0} [flags]\n", exeName); - Console.WriteLine("Available flags\n"); - Console.WriteLine("--help\t\t : Prints this help message."); - Console.WriteLine("examplename1 [examplename1 ...] : " + - "Run specific code examples. Example name can be one of the following:\n"); - foreach (SamplePair pair in sampleMap) { - Console.WriteLine("{0} : {1}", pair.Key, pair.Value.Description); - } - Console.WriteLine("Press [Enter] to continue"); - Console.ReadLine(); - } - } -} diff --git a/dotnet/v3.5/Properties/AssemblyInfo.cs b/dotnet/v3.5/Properties/AssemblyInfo.cs deleted file mode 100755 index 34bdabb..0000000 --- a/dotnet/v3.5/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("DfaReporting.Samples")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("DfaReporting.Samples")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e98d0eed-6c41-44d3-9739-bd2cee72f51b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet/v3.5/README.md b/dotnet/v3.5/README.md deleted file mode 100644 index ab05011..0000000 --- a/dotnet/v3.5/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# DCM/DFA Reporting and Trafficking API .NET Samples - -This is a collection of samples written in C# which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - -Install Visual Studio 2013+ and Nuget 2.12+ - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Running the Examples - -Once you've checked out the code: - -1. Open the DfaReporting.Samples.csproj file. - -2. Choose a sample and fill in any prerequisite values. Required values can be identified by the placeholder text: "ENTER_..._HERE". - -3. Add the sample name as a command line argument and build/run the project. - -4. Complete the authorization steps on your browser. - -5. Examine the console output, be inspired and start hacking an amazing new app! diff --git a/dotnet/v3.5/Remarketing/CreateRemarketingList.cs b/dotnet/v3.5/Remarketing/CreateRemarketingList.cs deleted file mode 100755 index 4c6a862..0000000 --- a/dotnet/v3.5/Remarketing/CreateRemarketingList.cs +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2017 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a remarketing list for a given advertiser and floodlight activity, using - /// a custom rule. - /// - /// Note: this sample assumes that the floodlight activity specified has a U1 custom floodlight - /// variable. - /// - class CreateRemarketingList : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a remarketing list for a given advertiser" + - " and floodlight activity, using a custom rule.\n\n" + - "Note: this sample assumes that the floodlight activity specified" + - " has a U1 custom floodlight variable.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateRemarketingList(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string remarketingListName = _T("INSERT_REMARKETING_LIST_NAME_HERE"); - - // Create the remarketing list. - RemarketingList remarketingList = new RemarketingList(); - remarketingList.Active = true; - remarketingList.AdvertiserId = advertiserId; - remarketingList.LifeSpan = 30L; - remarketingList.Name = remarketingListName; - - // Create a list population term. - // This term matches all visitors with a U1 value exactly matching "test_value". - ListPopulationTerm term = new ListPopulationTerm(); - term.Operator__ = "STRING_EQUALS"; - term.Type = "CUSTOM_VARIABLE_TERM"; - term.Value = "test_value"; - term.VariableName = "U1"; - - // Add the term to a list population clause. - ListPopulationClause clause = new ListPopulationClause(); - clause.Terms = new List { term }; - - // Add the clause to a list population rule. - // This rule will target all visitors who trigger the specified floodlight activity and - // satisfy the custom rule defined in the list population term. - ListPopulationRule rule = new ListPopulationRule(); - rule.FloodlightActivityId = floodlightActivityId; - rule.ListPopulationClauses = new List { clause }; - remarketingList.ListPopulationRule = rule; - - // Insert the remarketing list. - RemarketingList result = - service.RemarketingLists.Insert(remarketingList, profileId).Execute(); - - // Display the new remarketing list ID. - Console.WriteLine("Remarketing list with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Remarketing/GetRemarketingLists.cs b/dotnet/v3.5/Remarketing/GetRemarketingLists.cs deleted file mode 100755 index 2d59fe6..0000000 --- a/dotnet/v3.5/Remarketing/GetRemarketingLists.cs +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all remarketing lists owned by the specified advertiser. - /// - /// Note: the RemarketingLists resource will only return lists owned by the specified advertiser. - /// To see all lists that can be used for targeting ads (including those shared from other - /// accounts or advertisers), use the TargetableRemarketingLists resource instead. - /// - class GetRemarketingLists : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all remarketing lists owned by the specified advertiser." + - "\n\nNote: the RemarketingLists resource will only return lists owned by the" + - " specified advertiser. To see all lists that can be used for targeting ads" + - " including those shared from other accounts or advertisers), use the" + - " TargetableRemarketingLists resource instead.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetRemarketingLists(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,remarketingLists(accountId,advertiserId,id,name)"; - - RemarketingListsListResponse lists; - String nextPageToken = null; - - do { - // Create and execute the remaketing lists list request - RemarketingListsResource.ListRequest request = - service.RemarketingLists.List(profileId, advertiserId); - request.Fields = fields; - request.PageToken = nextPageToken; - lists = request.Execute(); - - foreach (RemarketingList list in lists.RemarketingLists) { - Console.WriteLine( - "Remarketing list with ID {0} and name \"{1}\" was found.", - list.Id, list.Name); - } - - // Update the next page token - nextPageToken = lists.NextPageToken; - } while (lists.RemarketingLists.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Remarketing/ShareRemarketingListToAdvertiser.cs b/dotnet/v3.5/Remarketing/ShareRemarketingListToAdvertiser.cs deleted file mode 100755 index a1f1093..0000000 --- a/dotnet/v3.5/Remarketing/ShareRemarketingListToAdvertiser.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example shares an existing remarketing list with the specified advertiser. - /// - class ShareRemarketingListToAdvertiser : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example shares an existing remarketing list with the specified" + - " advertiser.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new ShareRemarketingListToAdvertiser(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long remarketingListId = long.Parse(_T("INSERT_REMARKETING_LIST_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Load the existing share info. - RemarketingListShare share = - service.RemarketingListShares.Get(profileId, remarketingListId).Execute(); - - if(share.SharedAdvertiserIds == null) { - share.SharedAdvertiserIds = new List {}; - } - - if(!share.SharedAdvertiserIds.Contains(advertiserId)) { - share.SharedAdvertiserIds.Add(advertiserId); - - // Update the share info with the newly added advertiser ID. - RemarketingListShare result = - service.RemarketingListShares.Update(share, profileId).Execute(); - - Console.WriteLine( - "Remarketing list with ID {0} is now shared to advertiser ID(s): {1}.\n", - result.RemarketingListId, string.Join(", ", result.SharedAdvertiserIds)); - } else { - Console.WriteLine( - "Remarketing list with ID {0} is already shared to advertiser ID {1}.\n", - remarketingListId, advertiserId); - } - } - } -} diff --git a/dotnet/v3.5/Remarketing/TargetAdToRemarketingList.cs b/dotnet/v3.5/Remarketing/TargetAdToRemarketingList.cs deleted file mode 100755 index 6e1ff0e..0000000 --- a/dotnet/v3.5/Remarketing/TargetAdToRemarketingList.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example targets an ad to a remarketing list. - /// - /// The first targetable remarketing list, either owned by or shared to the ad's advertiser, - /// will be used. To create a remarketing list, see CreateRemarketingList.cs. To share a - /// remarketing list with the ad's advertiser, see ShareRemarketingListToAdvertiser.cs. - /// - class TargetAdToRemarketingList : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example targets an ad to a remarketing list.\n\nThe first targetable" + - " remarketing list, either owned by or shared to the ad's advertiser, will be used." + - " To create a remarketing list, see CreateRemarketingList.cs. To share a remarketing" + - " list with the ad's advertiser, see ShareRemarketingListToAdvertiser.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new TargetAdToRemarketingList(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long adId = long.Parse(_T("INSERT_AD_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - Ad ad = service.Ads.Get(profileId, adId).Execute(); - - TargetableRemarketingListsResource.ListRequest listRequest = - service.TargetableRemarketingLists.List(profileId, ad.AdvertiserId.Value); - listRequest.MaxResults = 1; - TargetableRemarketingListsListResponse lists = listRequest.Execute(); - - if(lists.TargetableRemarketingLists.Any()) { - // Select the first targetable remarketing list that was returned. - TargetableRemarketingList list = lists.TargetableRemarketingLists.First(); - - // Create a list targeting expression. - ListTargetingExpression expression = new ListTargetingExpression(); - expression.Expression = list.Id.ToString(); - - // Update the ad. - ad.RemarketingListExpression = expression; - Ad result = service.Ads.Update(ad, profileId).Execute(); - - Console.WriteLine( - "Ad with ID {0} updated to use remarketing list expression: {1}.\n", - result.Id, result.RemarketingListExpression.Expression); - } else { - Console.WriteLine("No targetable remarketing lists found for ad with ID {0}.\n", adId); - } - } - } -} diff --git a/dotnet/v3.5/Reports/CreateReport.cs b/dotnet/v3.5/Reports/CreateReport.cs deleted file mode 100755 index 22b7a2c..0000000 --- a/dotnet/v3.5/Reports/CreateReport.cs +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; -using Newtonsoft.Json; - -namespace DfaReporting.Samples { - /// - /// This example provides an end-to-end example of how to create and - /// configure a standard report. - /// - class CreateReport : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example provides an end-to-end example of how to create " + - "and configure a standard report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // 1. Create a report resource. - Report report = CreateReportResource(); - - // 2. Define the report criteria. - DefineReportCriteria(report); - - // 3. (optional) Look up compatible fields. - FindCompatibleFields(service, profileId, report); - - // 4. Add dimension filters to the report criteria. - AddDimensionFilters(service, profileId, report); - - // 5. Save the report resource. - InsertReportResource(service, profileId, report); - } - - private Report CreateReportResource() { - Report report = new Report(); - - // Set the required fields "name" and "type". - report.Name = "Example standard report"; - report.Type = "STANDARD"; - - // Set optional fields. - report.FileName = "example_report"; - report.Format = "CSV"; - - Console.WriteLine("Creating {0} report resource with name \"{1}\".", - report.Type, report.Name); - - return report; - } - - private void DefineReportCriteria(Report report) { - // Define a date range to report on. This example uses explicit start and - // end dates to mimic the "LAST_30_DAYS" relative date range. - DateRange dateRange = new DateRange(); - dateRange.EndDate = DateTime.Now.ToString("yyyy-MM-dd"); - dateRange.StartDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"); - - // Create a report criteria. - SortedDimension dimension = new SortedDimension(); - dimension.Name = "advertiser"; - - Report.CriteriaData criteria = new Report.CriteriaData(); - criteria.DateRange = dateRange; - criteria.Dimensions = new List() { dimension }; - criteria.MetricNames = new List() { - "clicks", - "impressions" - }; - - // Add the criteria to the report resource. - report.Criteria = criteria; - - Console.WriteLine("\nAdded report criteria:\n{0}", - JsonConvert.SerializeObject(criteria)); - } - - private void FindCompatibleFields(DfareportingService service, - long profileId, Report report) { - CompatibleFields fields = - service.Reports.CompatibleFields.Query(report, profileId).Execute(); - - ReportCompatibleFields reportFields = fields.ReportCompatibleFields; - - if(reportFields.Dimensions.Any()) { - // Add a compatible dimension to the report. - Dimension dimension = reportFields.Dimensions[0]; - SortedDimension sortedDimension = new SortedDimension(); - sortedDimension.Name = dimension.Name; - report.Criteria.Dimensions.Add(sortedDimension); - } else if (reportFields.Metrics.Any()) { - // Add a compatible metric to the report. - Metric metric = reportFields.Metrics[0]; - report.Criteria.MetricNames.Add(metric.Name); - } - - Console.WriteLine( - "\nUpdated report criteria (with compatible fields):\n{0}", - JsonConvert.SerializeObject(report.Criteria)); - } - - private void AddDimensionFilters(DfareportingService service, - long profileId, Report report) { - // Query advertiser dimension values for report run dates. - DimensionValueRequest request = new DimensionValueRequest(); - request.StartDate = report.Criteria.DateRange.StartDate; - request.EndDate = report.Criteria.DateRange.EndDate; - request.DimensionName = "advertiser"; - - DimensionValueList values = - service.DimensionValues.Query(request, profileId).Execute(); - - if (values.Items.Any()) { - // Add a value as a filter to the report criteria. - report.Criteria.DimensionFilters = new List() { - values.Items[0] - }; - } - - Console.WriteLine( - "\nUpdated report criteria (with valid dimension filters):\n{0}", - JsonConvert.SerializeObject(report.Criteria)); - } - - private void InsertReportResource(DfareportingService service, - long profileId, Report report) { - Report insertedReport = - service.Reports.Insert(report, profileId).Execute(); - - Console.WriteLine("\nSuccessfully inserted new report with ID {0}.", - insertedReport.Id); - } - } -} diff --git a/dotnet/v3.5/Reports/DeleteReport.cs b/dotnet/v3.5/Reports/DeleteReport.cs deleted file mode 100755 index 1e7e243..0000000 --- a/dotnet/v3.5/Reports/DeleteReport.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to delete a report. - /// - class DeleteReport : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to delete a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DeleteReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("ENTER_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Delete the report. - service.Reports.Delete(profileId, reportId).Execute(); - - // Display the new report ID. - Console.WriteLine("Report with ID {0} was successfully deleted.", reportId); - } - } -} diff --git a/dotnet/v3.5/Reports/DownloadFile.cs b/dotnet/v3.5/Reports/DownloadFile.cs deleted file mode 100755 index 6328f5f..0000000 --- a/dotnet/v3.5/Reports/DownloadFile.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Text; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; -using Google.Apis.Download; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to download a file. - /// - class DownloadFile : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to download a file.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new DownloadFile(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long fileId = long.Parse(_T("INSERT_FILE_ID_HERE")); - long reportId = long.Parse(_T("ENTER_REPORT_ID_HERE")); - - // Retrive the file metadata. - File file = service.Files.Get(reportId, fileId).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - // Create a get request. - FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize; - - // Execute the get request and download the file. - using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file), - System.IO.FileMode.Create, System.IO.FileAccess.Write)) { - getRequest.Download(outFile); - Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name); - } - } - } - - private string GenerateFileName(File file) { - // If no filename is specified, use the file ID instead. - string fileName = file.FileName; - if (String.IsNullOrEmpty(fileName)) { - fileName = file.Id.ToString(); - } - - String extension = "CSV".Equals(file.Format) ? ".csv" : ".xml"; - - return fileName + extension; - } - } -} diff --git a/dotnet/v3.5/Reports/FindAndDownloadFile.cs b/dotnet/v3.5/Reports/FindAndDownloadFile.cs deleted file mode 100644 index b1d769f..0000000 --- a/dotnet/v3.5/Reports/FindAndDownloadFile.cs +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2018 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example provides an end-to-end example of how to find and download a - /// report file. - /// - class FindAndDownloadFile: SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example provides an end-to-end example of how to find " + - "and download a report file.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new FindAndDownloadFile(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - long reportId = long.Parse(_T("INSERT_REPORT_ID_HERE")); - - // 1. Find a file to download. - File file = FindFile(service, profileId, reportId); - - if (file != null) { - // 2. (optional) Generate browser URL. - GenerateBrowserUrl(service, reportId, file.Id.Value); - - // 3. Directly download the file - DirectDownloadFile(service, reportId, file.Id.Value); - } else { - Console.WriteLine( - "No file found for profile ID {0} and report ID {1}.", - profileId, reportId); - } - } - - private File FindFile(DfareportingService service, long profileId, - long reportId) { - File target = null; - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - ReportsResource.FilesResource.ListRequest request = - service.Reports.Files.List(profileId, reportId); - request.PageToken = nextPageToken; - files = request.Execute(); - - foreach (File file in files.Items) { - if (IsTargetFile(file)) { - target = file; - break; - } - } - - // Update the next page token. - nextPageToken = files.NextPageToken; - } while (target == null - && files.Items.Any() - && !String.IsNullOrEmpty(nextPageToken)); - - if (target != null) { - Console.WriteLine("Found file {0} with filename \"{1}\".", - target.Id, target.FileName); - return target; - } - - Console.WriteLine( - "Unable to find file for profile ID {0} and report ID {1}.", - profileId, reportId); - return null; - } - - private bool IsTargetFile(File file) { - // Provide custom validation logic here. - // For example purposes, any file with REPORT_AVAILABLE status is - // considered valid. - return "REPORT_AVAILABLE".Equals(file.Status); - } - - private void GenerateBrowserUrl(DfareportingService service, long reportId, - long fileId) { - File file = service.Files.Get(reportId, fileId).Execute(); - String browserUrl = file.Urls.BrowserUrl; - - Console.WriteLine("File {0} has browser URL: {1}.", file.Id, browserUrl); - } - - private void DirectDownloadFile(DfareportingService service, long reportId, - long fileId) { - // Retrieve the file metadata. - File file = service.Files.Get(reportId, fileId).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - // Create a get request. - FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize; - - // Execute the get request and download the file. - using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file), - System.IO.FileMode.Create, System.IO.FileAccess.Write)) { - getRequest.Download(outFile); - Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name); - } - } - } - - private string GenerateFileName(File file) { - // If no filename is specified, use the file ID instead. - string fileName = file.FileName; - if (String.IsNullOrEmpty(fileName)) { - fileName = file.Id.ToString(); - } - - String extension = "CSV".Equals(file.Format) ? ".csv" : ".xml"; - - return fileName + extension; - } - } -} diff --git a/dotnet/v3.5/Reports/FindAndRunReport.cs b/dotnet/v3.5/Reports/FindAndRunReport.cs deleted file mode 100644 index c9195f7..0000000 --- a/dotnet/v3.5/Reports/FindAndRunReport.cs +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2018 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using System.Threading; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example provides an end-to-end example of how to find and run a - /// report. - /// - class FindAndRunReport : SampleBase { - // The following values control retry behavior while the report is processing. - // Minimum amount of time between polling requests. Defaults to 10 seconds. - private static int MIN_RETRY_INTERVAL = 10; - // Maximum amount of time between polling requests. Defaults to 10 minutes. - private static int MAX_RETRY_INTERVAL = 10 * 60; - // Maximum amount of time to spend polling. Defaults to 1 hour. - private static int MAX_RETRY_ELAPSED_TIME = 60 * 60; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example provides an end-to-end example of how to find " + - "and run a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new FindAndRunReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // 1. Find a report to run. - Report report = FindReport(service, profileId); - - if (report != null) { - // 2. Run the report. - File file = RunReport(service, profileId, report.Id.Value); - - // 3. Wait for the report file to be ready. - WaitForReportFile(service, report.Id.Value, file.Id.Value); - } else { - Console.WriteLine("No report found for profile ID {0}.", profileId); - } - } - - private Report FindReport(DfareportingService service, long profileId) { - Report target = null; - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the reports list request. - ReportsResource.ListRequest request = service.Reports.List(profileId); - request.PageToken = nextPageToken; - reports = request.Execute(); - - foreach (Report report in reports.Items) { - if (IsTargetReport(report)) { - target = report; - break; - } - } - - // Update the next page token. - nextPageToken = reports.NextPageToken; - } while (target == null - && reports.Items.Any() - && !String.IsNullOrEmpty(nextPageToken)); - - if (target != null) { - Console.WriteLine("Found report {0} with name \"{1}\".", - target.Id, target.Name); - return target; - } - - Console.WriteLine("Unable to find report for profile ID {0}.", profileId); - return null; - } - - private bool IsTargetReport(Report report) { - // Provide custom validation logic here. - // For example purposes, any report is considered valid. - return true; - } - - private File RunReport(DfareportingService service, long profileId, - long reportId) { - // Run the report. - File file = service.Reports.Run(profileId, reportId).Execute(); - - Console.WriteLine("Running report {0}, current file status is {1}.", - reportId, file.Status); - return file; - } - - private void WaitForReportFile(DfareportingService service, long reportId, - long fileId) { - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve quota. - int sleep = 0; - int startTime = GetCurrentTimeInSeconds(); - do { - File file = service.Files.Get(reportId, fileId).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - Console.WriteLine("File status is {0}, ready to download.", file.Status); - return; - } else if (!"PROCESSING".Equals(file.Status)) { - Console.WriteLine("File status is {0}, processing failed.", file.Status); - return; - } else if (GetCurrentTimeInSeconds() - startTime > MAX_RETRY_ELAPSED_TIME) { - Console.WriteLine("File processing deadline exceeded."); - return; - } - - sleep = GetNextSleepInterval(sleep); - Console.WriteLine("File status is {0}, sleeping for {1} seconds.", file.Status, sleep); - Thread.Sleep(sleep * 1000); - } while (true); - } - - private int GetCurrentTimeInSeconds() { - return (int) (DateTime.Now.Ticks / TimeSpan.TicksPerSecond); - } - - private int GetNextSleepInterval(int previousSleepInterval) { - int minInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval); - int maxInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval * 3); - return Math.Min(MAX_RETRY_INTERVAL, new Random().Next(minInterval, maxInterval)); - } - } -} diff --git a/dotnet/v3.5/Reports/GetCompatibleFields.cs b/dotnet/v3.5/Reports/GetCompatibleFields.cs deleted file mode 100755 index a2a47b7..0000000 --- a/dotnet/v3.5/Reports/GetCompatibleFields.cs +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get the compatible fields for a standard - /// report. - /// - class GetCompatibleFields : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get the compatible fields" + - " for a standard report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetCompatibleFields(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("ENTER_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Retrieve the specified report. - Report report = service.Reports.Get(profileId, reportId).Execute(); - - // Look up the compatible fields for the report. - CompatibleFields fields = - service.Reports.CompatibleFields.Query(report, profileId).Execute(); - - // Display the compatible fields, assuming this is a standard report. - ReportCompatibleFields reportFields = fields.ReportCompatibleFields; - - Console.WriteLine("Compatible dimensions:\n"); - printDimensionNames(reportFields.Dimensions); - - Console.WriteLine("\nCompatible metrics:\n"); - printMetricNames(reportFields.Metrics); - - Console.WriteLine("\nCompatible dimension filters:\n"); - printDimensionNames(reportFields.DimensionFilters); - - Console.WriteLine("\nCompatible pivoted activity metrics:\n"); - printMetricNames(reportFields.PivotedActivityMetrics); - } - - private static void printDimensionNames(IList dimensions) { - foreach (Dimension dimension in dimensions) { - Console.WriteLine(dimension.Name); - } - } - - private static void printMetricNames(IList metrics) { - foreach (Metric metric in metrics) { - Console.WriteLine(metric.Name); - } - } - } -} diff --git a/dotnet/v3.5/Reports/GetDimensionValues.cs b/dotnet/v3.5/Reports/GetDimensionValues.cs deleted file mode 100755 index 24e92af..0000000 --- a/dotnet/v3.5/Reports/GetDimensionValues.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get all dimension values for a dimension. - /// - class GetDimensionValues : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get all dimension values for" + - " a dimension.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetDimensionValues(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(id,value)"; - - // Construct the dimension value request. - DimensionValueRequest request = new DimensionValueRequest(); - request.DimensionName = "advertiser"; - - // Set the date range from 1 year ago until today. - request.StartDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now.AddYears(-1)); - request.EndDate = - DfaReportingDateConverterUtil.convertToDateString(DateTime.Now); - - DimensionValueList values; - String nextPageToken = null; - - do { - // Create and execute the dimension value query request. - DimensionValuesResource.QueryRequest query = - service.DimensionValues.Query(request, profileId); - query.Fields = fields; - query.PageToken = nextPageToken; - values = query.Execute(); - - foreach (DimensionValue value in values.Items) { - Console.WriteLine("Dimension value with ID {0} and value \"{1}\" was found.", - value.Id, value.Value); - } - - // Update the next page token. - nextPageToken = values.NextPageToken; - } while (values.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Reports/GetFiles.cs b/dotnet/v3.5/Reports/GetFiles.cs deleted file mode 100755 index 295f296..0000000 --- a/dotnet/v3.5/Reports/GetFiles.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all the files for a profile. - /// - class GetFiles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all the files" + - " for a profile.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetFiles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - FilesResource.ListRequest request = service.Files.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - files = request.Execute(); - - foreach (File file in files.Items) { - Console.WriteLine("Report file with ID {0} and file name \"{1}\" has status \"{2}\".", - file.Id, file.FileName, file.Status); - } - - // Update the next page token. - nextPageToken = files.NextPageToken; - } while (files.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Reports/GetReportFiles.cs b/dotnet/v3.5/Reports/GetReportFiles.cs deleted file mode 100755 index 8d95562..0000000 --- a/dotnet/v3.5/Reports/GetReportFiles.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all the files for a report. - /// - class GetReportFiles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all the files" + - " for a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetReportFiles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("INSERT_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the report files list request. - ReportsResource.FilesResource.ListRequest request = - service.Reports.Files.List(profileId, reportId); - request.Fields = fields; - request.PageToken = nextPageToken; - files = request.Execute(); - - foreach (File file in files.Items) { - Console.WriteLine("Report file with ID {0} and file name \"{1}\" has status \"{2}\".", - file.Id, file.FileName, file.Status); - } - - // Update the next page token. - nextPageToken = files.NextPageToken; - } while (files.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Reports/GetReports.cs b/dotnet/v3.5/Reports/GetReports.cs deleted file mode 100755 index 79f586d..0000000 --- a/dotnet/v3.5/Reports/GetReports.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all reports. - /// - class GetReports : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all reports.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetReports(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,items(id,name,type)"; - - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the report list request. - ReportsResource.ListRequest request = service.Reports.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - reports = request.Execute(); - - foreach (Report report in reports.Items) { - Console.WriteLine("{0} report with ID {1} and name \"{2}\" was found.", - report.Type, report.Id, report.Name); - } - - // Update the next page token. - nextPageToken = reports.NextPageToken; - } while (reports.Items.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Reports/RunReport.cs b/dotnet/v3.5/Reports/RunReport.cs deleted file mode 100755 index 3eb29d5..0000000 --- a/dotnet/v3.5/Reports/RunReport.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Threading; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to run a report. - /// - class RunReport : SampleBase { - // The following values control retry behavior while the report is processing. - // Minimum amount of time between polling requests. Defaults to 10 seconds. - private static int MIN_RETRY_INTERVAL = 10; - // Maximum amount of time between polling requests. Defaults to 10 minutes. - private static int MAX_RETRY_INTERVAL = 10 * 60; - // Maximum amount of time to spend polling. Defaults to 1 hour. - private static int MAX_RETRY_ELAPSED_TIME = 60 * 60; - - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to run a report.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new RunReport(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long reportId = long.Parse(_T("INSERT_REPORT_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Run the report. - File file = service.Reports.Run(profileId, reportId).Execute(); - Console.WriteLine("File with ID {0} has been created.", file.Id); - - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve quota. - int sleep = 0; - int startTime = GetCurrentTimeInSeconds(); - do { - file = service.Files.Get(file.ReportId.Value, file.Id.Value).Execute(); - - if ("REPORT_AVAILABLE".Equals(file.Status)) { - Console.WriteLine("File status is {0}, ready to download.", file.Status); - return; - } else if (!"PROCESSING".Equals(file.Status)) { - Console.WriteLine("File status is {0}, processing failed.", file.Status); - return; - } else if (GetCurrentTimeInSeconds() - startTime > MAX_RETRY_ELAPSED_TIME) { - Console.WriteLine("File processing deadline exceeded."); - return; - } - - sleep = GetNextSleepInterval(sleep); - Console.WriteLine("File status is {0}, sleeping for {1} seconds.", file.Status, sleep); - Thread.Sleep(sleep * 1000); - } while (true); - } - - private int GetCurrentTimeInSeconds() { - return (int) (DateTime.Now.Ticks / TimeSpan.TicksPerSecond); - } - - private int GetNextSleepInterval(int previousSleepInterval) { - int minInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval); - int maxInterval = Math.Max(MIN_RETRY_INTERVAL, previousSleepInterval * 3); - return Math.Min(MAX_RETRY_INTERVAL, new Random().Next(minInterval, maxInterval)); - } - } -} diff --git a/dotnet/v3.5/SampleBase.cs b/dotnet/v3.5/SampleBase.cs deleted file mode 100755 index b4517bb..0000000 --- a/dotnet/v3.5/SampleBase.cs +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -// Comment out the following define to make the samples non-interactive. -// This will require you to manually replace the INSERT_XXX fields in -// samples. -#define INTERACTIVE - -using System; -using Google.Apis.Dfareporting.v3_5; - -namespace DfaReporting.Samples { - /// - /// This abstract class represents a code example. - /// - abstract class SampleBase { - /// - /// Returns a description about the code example. - /// - public abstract string Description { - get; - } - - /// - /// Run the code example. - /// - /// A Dfa Reporting service instance. - public abstract void Run(DfareportingService service); - - protected string _T(string prompt) { -#if INTERACTIVE - Console.Write(prompt + " : "); - return Console.ReadLine(); -#else - return prompt; -#endif - } - } -} diff --git a/dotnet/v3.5/Subaccounts/CreateSubaccount.cs b/dotnet/v3.5/Subaccounts/CreateSubaccount.cs deleted file mode 100755 index 55d8698..0000000 --- a/dotnet/v3.5/Subaccounts/CreateSubaccount.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a subaccount in a given DoubleClick Campaign Manager - /// account. To get the available permissions, run - /// GetUserRolePermissions.cs. - /// - class CreateSubaccount : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a subaccount in a given DoubleClick" + - " Campaign Manager account. To get the available permissions, run" + - " GetSubaccountPermissions.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateSubaccount(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long accountId = long.Parse(_T("INSERT_ACCOUNT_ID_HERE")); - long permissionOneId = long.Parse(_T("INSERT_FIRST_PERMISSION_ID_HERE")); - long permissionTwoId = long.Parse(_T("INSERT_SECOND_PERMISSION_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - String subaccountName = _T("INSERT_SUBACCOUNT_NAME_HERE"); - - // Create subaccount structure. - Subaccount subaccount = new Subaccount(); - subaccount.Name = subaccountName; - subaccount.AccountId = accountId; - - // Create a collection of all permissions assigned to this subaccount and add it to the - // subaccount structure. To get list of available permissions, run GetUserRolePermissions.cs. - subaccount.AvailablePermissionIds = new List { permissionOneId, permissionTwoId }; - - // Create subaccount. - Subaccount result = service.Subaccounts.Insert(subaccount, profileId).Execute(); - - // Display subaccount ID. - Console.WriteLine("Subaccount with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Subaccounts/GetSubaccountPermissions.cs b/dotnet/v3.5/Subaccounts/GetSubaccountPermissions.cs deleted file mode 100755 index b9c176a..0000000 --- a/dotnet/v3.5/Subaccounts/GetSubaccountPermissions.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all of the available subaccount permissions. - /// - /// To get a subaccount ID, run GetSubaccounts.cs. - /// - class GetSubaccountPermissions : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all of the available user role permissions for the" + - " specified subaccount.\n\nTo get a subaccount ID, run GetSubaccounts.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSubaccountPermissions(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - long subaccountId = long.Parse(_T("INSERT_SUBACCOUNT_ID_HERE")); - - // Limit the fields returned. - String fields = "userRolePermissions(id,name)"; - - // Retrieve the subaccount. - Subaccount subaccount = service.Subaccounts.Get(profileId, subaccountId).Execute(); - - // Retrieve the subaccount permissions. - UserRolePermissionsResource.ListRequest request = service.UserRolePermissions.List(profileId); - request.Ids = subaccount.AvailablePermissionIds.Select(p => p.ToString()).ToList(); - request.Fields = fields; - - UserRolePermissionsListResponse permissions = request.Execute(); - - // Display the subaccount permissions. - foreach (UserRolePermission permission in permissions.UserRolePermissions) { - Console.WriteLine("User role permission with ID {0} and name \"{1}\" was found.", - permission.Id, permission.Name); - } - } - } -} diff --git a/dotnet/v3.5/Subaccounts/GetSubaccounts.cs b/dotnet/v3.5/Subaccounts/GetSubaccounts.cs deleted file mode 100755 index 287c244..0000000 --- a/dotnet/v3.5/Subaccounts/GetSubaccounts.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all subaccounts. - /// - /// Note that the permissions assigned to a subaccount are not returned in a - /// human-readable format with this example. Run GetUserRolePermissions.cs - /// to see what permissions are available on a subaccount. - /// - class GetSubaccounts : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all subaccounts.\n\n" + - "Note that the permissions assigned to a subaccount are not returned" + - " in a human-readable format with this example. Run" + - " GetUserRolePermissions.cs to see what permissions are available" + - " on a subaccount.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetSubaccounts(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,subaccounts(id,name)"; - - SubaccountsListResponse subaccounts; - String nextPageToken = null; - - do { - // Create and execute the subaccounts list request. - SubaccountsResource.ListRequest request = service.Subaccounts.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - subaccounts = request.Execute(); - - foreach (Subaccount subaccount in subaccounts.Subaccounts) { - Console.WriteLine("Subaccount with ID {0} and name \"{1}\" was found.", subaccount.Id, - subaccount.Name); - } - - // Update the next page token. - nextPageToken = subaccounts.NextPageToken; - } while (subaccounts.Subaccounts.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/Targeting/ConfigureDynamicAssetTargeting.cs b/dotnet/v3.5/Targeting/ConfigureDynamicAssetTargeting.cs deleted file mode 100755 index dd0ae8f..0000000 --- a/dotnet/v3.5/Targeting/ConfigureDynamicAssetTargeting.cs +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example uploads a new video asset to an existing in-stream video creative and configures - /// dynamic asset selection, using a specified targeting template. To get an in-stream video - /// creative, run CreateInstreamVideoCreative.cs. To get a targeting template, run - /// CreateTargetingTemplate.cs. - /// - class ConfigureDynamicAssetTargeting : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example uploads a new video asset to an existing in-stream video creative " + - "and configures dynamic asset selection, using a specified targeting template. To " + - "get an in-stream video creative, run CreateInstreamVideoCreative.cs. To get a " + - "targeting template, run CreateTargetingTemplate.cs."; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new ConfigureDynamicAssetTargeting(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long instreamVideoCreativeId = long.Parse(_T("INSERT_INSTREAM_VIDEO_CREATIVE_ID_HERE")); - long targetingTemplateId = long.Parse(_T("INSERT_TARGETING_TEMPLATE_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string videoAssetName = _T("INSERT_VIDEO_ASSET_NAME_HERE"); - string pathToVideoAssetFile = _T("INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"); - - // Retrieve the specified creative. - Creative creative = service.Creatives.Get(profileId, instreamVideoCreativeId).Execute(); - if (creative == null || !"INSTREAM_VIDEO".Equals(creative.Type)) { - Console.Error.WriteLine("Invalid creative specified."); - return; - } - - CreativeAssetSelection selection = creative.CreativeAssetSelection; - if (!creative.DynamicAssetSelection.Value) { - // Locate an existing video asset to use as a default. - // This example uses the first PARENT_VIDEO asset found. - CreativeAsset defaultAsset = - creative.CreativeAssets.First(asset => "PARENT_VIDEO".Equals(asset.Role)); - if (defaultAsset == null) { - Console.Error.WriteLine("Default video asset could not be found."); - return; - } - - // Create a new selection using the existing asset as a default. - selection = new CreativeAssetSelection(); - selection.DefaultAssetId = defaultAsset.Id; - selection.Rules = new List(); - - // Enable dynamic asset selection for the creative. - creative.DynamicAssetSelection = true; - creative.CreativeAssetSelection = selection; - } - - // Upload the new video asset and add it to the creative. - CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, - creative.AdvertiserId.Value); - CreativeAssetMetadata videoMetadata = assetUtils.uploadAsset(pathToVideoAssetFile, "VIDEO"); - creative.CreativeAssets.Add(new CreativeAsset() { - AssetIdentifier = videoMetadata.AssetIdentifier, - Role = "PARENT_VIDEO" - }); - - // Create a rule targeting the new video asset and add it to the selection. - Rule rule = new Rule(); - rule.AssetId = videoMetadata.Id; - rule.Name = "Test rule for asset " + videoMetadata.Id; - rule.TargetingTemplateId = targetingTemplateId; - selection.Rules.Add(rule); - - // Update the creative. - Creative result = service.Creatives.Update(creative, profileId).Execute(); - Console.WriteLine("Dynamic asset selection enabled for creative with ID {0}.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Targeting/CreateTargetingTemplate.cs b/dotnet/v3.5/Targeting/CreateTargetingTemplate.cs deleted file mode 100755 index 9a171d9..0000000 --- a/dotnet/v3.5/Targeting/CreateTargetingTemplate.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a basic targeting template associated with a given advertiser. To get an - /// advertiser ID, run GetAdvertisers.cs. - /// - class CreateTargetingTemplate : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a basic targeting template associated with a given " + - "advertiser. To get an advertiser ID, run GetAdvertisers.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateTargetingTemplate(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - string targetingTemplateName = _T("INSERT_TARGETING_TEMPLATE_NAME_HERE"); - - // Create the targeting template. - TargetingTemplate template = new TargetingTemplate(); - template.AdvertiserId = advertiserId; - template.Name = targetingTemplateName; - - // Configure the template to serve ads on Monday, Wednesday, and Friday from 9-10am - // and 3-5pm. - DayPartTargeting dayTargeting = new DayPartTargeting(); - dayTargeting.DaysOfWeek = new List() { "MONDAY", "WEDNESDAY", "FRIDAY" }; - dayTargeting.HoursOfDay = new List() { 9, 15, 16 }; - dayTargeting.UserLocalTime = true; - template.DayPartTargeting = dayTargeting; - - // Insert the targeting template. - TargetingTemplate result = service.TargetingTemplates.Insert(template, profileId).Execute(); - - // Display the new targeting template ID. - Console.WriteLine("Targeting template with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/Targeting/GetTargetingTemplates.cs b/dotnet/v3.5/Targeting/GetTargetingTemplates.cs deleted file mode 100755 index c45dd12..0000000 --- a/dotnet/v3.5/Targeting/GetTargetingTemplates.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2016 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays the name, ID and advertiser ID for every targeting template your DCM - /// user profile can see. - /// - class GetTargetingTemplates : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays the name, ID and advertiser ID for every targeting " + - "template your DCM user profile can see.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetTargetingTemplates(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,targetingTemplates(advertiserId,id,name)"; - - TargetingTemplatesListResponse templates; - String nextPageToken = null; - - do { - // Create and execute the placements list request - TargetingTemplatesResource.ListRequest request = - service.TargetingTemplates.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - templates = request.Execute(); - - foreach (TargetingTemplate template in templates.TargetingTemplates) { - Console.WriteLine( - "Targeting template {0} and name \"{1}\" is associated with advertiser ID {2}.", - template.Id, template.Name, template.AdvertiserId); - } - - // Update the next page token - nextPageToken = templates.NextPageToken; - } while (templates.TargetingTemplates.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/UserProfiles/GetUserProfiles.cs b/dotnet/v3.5/UserProfiles/GetUserProfiles.cs deleted file mode 100755 index d851aac..0000000 --- a/dotnet/v3.5/UserProfiles/GetUserProfiles.cs +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example illustrates how to get a list of all user profiles. - /// - class GetUserProfiles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example illustrates how to get a list of all user profiles.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetUserProfiles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = service.UserProfiles.List().Execute(); - foreach (UserProfile profile in profiles.Items) { - Console.WriteLine("User profile with ID {0} and name \"{1}\" was found for account {2}.", - profile.ProfileId, profile.UserName, profile.AccountId); - } - } - } -} diff --git a/dotnet/v3.5/UserRoles/CreateUserRole.cs b/dotnet/v3.5/UserRoles/CreateUserRole.cs deleted file mode 100755 index ac0e2cd..0000000 --- a/dotnet/v3.5/UserRoles/CreateUserRole.cs +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example creates a user role in a given DoubleClick Campaign Manager - /// subaccount. To get the subaccount ID, run GetSubaccounts.cs. To get the - /// available permissions, run GetUserRolePermissions.cs. To get the parent - /// user role ID, run GetUserRoles.cs. - /// - class CreateUserRole : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example creates a user role in a given DoubleClick" + - " Campaign Manager subaccount. To get the subaccount ID, run" + - " GetSubaccounts.cs. To get the available permissions, run" + - " GetUserRolePermissions.cs. To get the parent user role ID, run" + - " GetUserRoles.cs.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new CreateUserRole(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long parentUserRoleId = long.Parse(_T("INSERT_PARENT_USER_ROLE_ID_HERE")); - long permission1Id = long.Parse(_T("INSERT_FIRST_PERMISSION_ID_HERE")); - long permission2Id = long.Parse(_T("INSERT_SECOND_PERMISSIONS_ID_HERE")); - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - long subaccountId = long.Parse(_T("INSERT_SUBACCOUNT_ID_HERE")); - - String userRoleName = _T("INSERT_USER_ROLE_NAME_HERE"); - - // Create user role structure. - UserRole userRole = new UserRole(); - userRole.Name = userRoleName; - userRole.SubaccountId = subaccountId; - userRole.ParentUserRoleId = parentUserRoleId; - - // Create a permission object to represent each permission this user role - // has. - UserRolePermission permission1 = new UserRolePermission(); - permission1.Id = permission1Id; - UserRolePermission permission2 = new UserRolePermission(); - permission2.Id = permission2Id; - List permissions = - new List { permission1, permission2 }; - - // Add the permissions to the user role. - userRole.Permissions = permissions; - - // Create user role. - UserRole result = service.UserRoles.Insert(userRole, profileId).Execute(); - - // Display user role ID. - Console.WriteLine("User role with ID {0} was created.", result.Id); - } - } -} diff --git a/dotnet/v3.5/UserRoles/GetUserRoles.cs b/dotnet/v3.5/UserRoles/GetUserRoles.cs deleted file mode 100755 index fe00210..0000000 --- a/dotnet/v3.5/UserRoles/GetUserRoles.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Google Inc - * - * Licensed under the Apache License, Version 2.0(the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -using System; -using System.Linq; -using Google.Apis.Dfareporting.v3_5; -using Google.Apis.Dfareporting.v3_5.Data; - -namespace DfaReporting.Samples { - /// - /// This example displays all user roles. - /// - /// The output is limited to include only ID, name, account ID and subaccount ID. - /// - class GetUserRoles : SampleBase { - /// - /// Returns a description about the code example. - /// - public override string Description { - get { - return "This example displays all user roles.\n\n" + - "The output is limited to include only ID, name, account ID and" + - " subaccount ID.\n"; - } - } - - /// - /// Main method, to run this code example as a standalone application. - /// - /// The command line arguments. - public static void Main(string[] args) { - SampleBase codeExample = new GetUserRoles(); - Console.WriteLine(codeExample.Description); - codeExample.Run(DfaReportingFactory.getInstance()); - } - - /// - /// Run the code example. - /// - /// An initialized Dfa Reporting service object - /// - public override void Run(DfareportingService service) { - long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); - - // Limit the fields returned. - String fields = "nextPageToken,userRoles(accountId,id,name,subaccountId)"; - - UserRolesListResponse roles; - String nextPageToken = null; - - do { - // Create and execute the user roles list request. - UserRolesResource.ListRequest request = service.UserRoles.List(profileId); - request.Fields = fields; - request.PageToken = nextPageToken; - - roles = request.Execute(); - - foreach (UserRole role in roles.UserRoles) { - Console.WriteLine("User role with ID {0} and name \"{1}\" was found.", role.Id, - role.Name); - } - - // Update the next page token. - nextPageToken = roles.NextPageToken; - } while (roles.UserRoles.Any() && !String.IsNullOrEmpty(nextPageToken)); - } - } -} diff --git a/dotnet/v3.5/app.config b/dotnet/v3.5/app.config deleted file mode 100755 index 87fd34f..0000000 --- a/dotnet/v3.5/app.config +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dotnet/v3.5/client_secrets.json b/dotnet/v3.5/client_secrets.json deleted file mode 100755 index 63d282d..0000000 --- a/dotnet/v3.5/client_secrets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "installed": { - "client_id": "Enter Client ID", - "client_secret": "Enter Client Secret" - } -} \ No newline at end of file diff --git a/dotnet/v3.5/packages.config b/dotnet/v3.5/packages.config deleted file mode 100644 index 82f34aa..0000000 --- a/dotnet/v3.5/packages.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/gen_sample_targets.bzl b/gen_sample_targets.bzl index 8bd8db4..284f5af 100644 --- a/gen_sample_targets.bzl +++ b/gen_sample_targets.bzl @@ -39,7 +39,7 @@ def gen_java_targets(name): "name": versioned_rule_name, "srcs": native.glob(["%s/**/*.java" % version]), "deps": COMMON_JAVA_SAMPLE_DEPS + [ - "//google/ads/xfa/dfareporting:dfareporting-java-client-%s" % java_client_version, + "//google/ads/xfa/dfareporting/op:dfareporting-java-client-%s" % java_client_version, ], } diff --git a/java/v3.4/README.md b/java/v3.4/README.md deleted file mode 100644 index a0a7c32..0000000 --- a/java/v3.4/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# DCM/DFA Reporting and Trafficking API Java Samples - -This is a collection of samples written in Java which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - -Please make sure that you're running Java 7+ and have maven installed. - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Set up your environment ## -### Via the command line ### - -1. Execute the following command: - - ```Batchfile - $ mvn compile - ``` - -### Via Eclipse ### - -1. Setup Eclipse preferences: - 1. Window > Preferences .. (or on Mac, Eclipse > Preferences) - 2. Select Maven - 3. Select "Download Artifact Sources" - 4. Select "Download Artifact JavaDoc" -2. Import the sample project - 1. File > Import... - 2. Select General > Existing Project into Workspace and click "Next" - 3. Click "Browse" next to "Select root directory", find the sample directory and click "Next" - 4. Click "Finish" - -## Running the Examples - -Once you've checked out the code: - -1. Open a sample and fill in any prerequisite values. Required values will be declared as constants near the top of the file. - -2. Run the sample - - 1. Via eclipse, right-click on the project and select Run As > Java Application - -3. Complete the authorization steps on your browser - -4. Examine the console output, be inspired and start hacking an amazing new app! diff --git a/java/v3.4/logging.properties b/java/v3.4/logging.properties deleted file mode 100644 index 08656ce..0000000 --- a/java/v3.4/logging.properties +++ /dev/null @@ -1,10 +0,0 @@ -# Properties file which configures the operation of the JDK logging facility. -# The system will look for this config file to be specified as a system property: -# -Djava.util.logging.config.file=${project_loc:dfareporting-java-sample}/logging.properties - -# Set up the console handler (uncomment "level" to show more fine-grained messages) -handlers = java.util.logging.ConsoleHandler -#java.util.logging.ConsoleHandler.level = CONFIG - -# Set up logging of HTTP requests and responses (uncomment "level" to show) -#com.google.api.client.http.level = CONFIG diff --git a/java/v3.4/pom.xml b/java/v3.4/pom.xml deleted file mode 100644 index 0ce5c98..0000000 --- a/java/v3.4/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - 4.0.0 - com.google.apis-samples - dfareporting-java-sample - 1.0.0 - Samples for the DFA Reporting and Trafficking API using JSON and OAuth 2.0 - - 2015 - - - 2.0.9 - - - - - jimper - Jonathon Imperiosi - jimper@users.noreply.github.com - Google - http://www.google.com - - owner - developer - - -5 - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - org.codehaus.mojo - exec-maven-plugin - 1.1 - - - - java - - - - - - org.codehaus.mojo - findbugs-maven-plugin - 2.3.2 - - false - - - - - check - - - - - - ${project.artifactId}-${project.version} - - - - com.google.apis - google-api-services-dfareporting - v3.4-rev20200514-1.30.10 - - - com.google.guava - guava-jdk5 - - - - - com.google.http-client - google-http-client-jackson2 - ${project.http.version} - - - com.google.apis - google-api-services-oauth2 - v1-rev155-1.25.0 - - - com.google.oauth-client - google-oauth-client-jetty - ${project.oauth.version} - - - com.google.guava - guava - 29.0-android - - - - 1.28.0 - 1.28.0 - UTF-8 - - diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/DfaReportingFactory.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/DfaReportingFactory.java deleted file mode 100644 index d0aac5d..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/DfaReportingFactory.java +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; -import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; -import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; -import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.util.store.DataStoreFactory; -import com.google.api.client.util.store.FileDataStoreFactory; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.DfareportingScopes; - -import java.io.IOException; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.Paths; - -/** - * Utility methods used by all DFA Reporting and Trafficking API samples. - */ -public class DfaReportingFactory { - /** Directory to store user credentials. */ - private static final java.io.File DATA_STORE_DIR = - new java.io.File(System.getProperty("user.home"), ".store/dfareporting_sample"); - - private static final HttpTransport HTTP_TRANSPORT = Utils.getDefaultTransport(); - private static final JsonFactory JSON_FACTORY = Utils.getDefaultJsonFactory(); - - /** - * Authorizes the application to access users' protected data. - * - * @return An initialized {@link Credential} object. - */ - private static Credential authorize() throws Exception { - // Load application default credentials if they're available. - Credential credential = loadApplicationDefaultCredentials(); - - // Otherwise, load credentials from the provided client secrets file. - if (credential == null) { - String clientSecretsFile = - DfaReportingFactory.class.getResource("/client_secrets.json").getFile(); - credential = loadUserCredentials(clientSecretsFile, new FileDataStoreFactory(DATA_STORE_DIR)); - } - - return credential; - } - - /** - * Attempts to load application default credentials. - * - * @return A {@link Credential} object initialized with application default credentials, or - * {@code null} if none were found. - */ - private static Credential loadApplicationDefaultCredentials() { - try { - GoogleCredential credential = GoogleCredential.getApplicationDefault(); - return credential.createScoped(DfareportingScopes.all()); - } catch (IOException ignored) { - // No application default credentials, continue to try other options. - } - - return null; - } - - /** - * Attempts to load user credentials from the provided client secrets file and persists data to - * the provided data store. - * - * @param clientSecretsFile The path to the file containing client secrets. - * @param dataStoreFactory he data store to use for caching credential information. - * @return A {@link Credential} object initialized with user account credentials. - */ - private static Credential loadUserCredentials(String clientSecretsFile, - DataStoreFactory dataStoreFactory) throws Exception { - // Load client secrets JSON file. - GoogleClientSecrets clientSecrets; - try (Reader reader = Files.newBufferedReader(Paths.get(clientSecretsFile), UTF_8)) { - clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, reader); - } - - // Set up the authorization code flow. - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, - JSON_FACTORY, clientSecrets, DfareportingScopes.all()) - .setDataStoreFactory(dataStoreFactory) - .build(); - - // Authorize and persist credential information to the data store. - return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); - } - - /** - * Performs all necessary setup steps for running requests against the API. - * - * @return An initialized {@link Dfareporting} service object. - */ - public static Dfareporting getInstance() throws Exception { - Credential credential = authorize(); - - // Create Dfareporting client. - return new Dfareporting.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName( - "dfareporting-java-samples").build(); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/ads/CreateRotationGroup.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/ads/CreateRotationGroup.java deleted file mode 100755 index 8f9d756..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/ads/CreateRotationGroup.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.ads; - -import com.google.api.client.util.DateTime; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Ad; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.ClickThroughUrl; -import com.google.api.services.dfareporting.model.CreativeAssignment; -import com.google.api.services.dfareporting.model.CreativeRotation; -import com.google.api.services.dfareporting.model.DeliverySchedule; -import com.google.api.services.dfareporting.model.PlacementAssignment; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -import java.util.Date; - -/** - * This example creates a rotation group ad in a given campaign. Start and end date for the ad must - * be within campaign start and end dates. To create creatives, run one of the Create*Creative.java - * examples. To get available placements, run GetPlacements.java. - */ -public class CreateRotationGroup { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - // Set the parameters for the new ad rotation group. - private static final String AD_NAME = "ENTER_AD_NAME_HERE"; - private static final String CAMPAIGN_ID = "ENTER_CAMPAIGN_ID_HERE"; - private static final String CREATIVE_ID = "ENTER_CREATIVE_ID_HERE"; - private static final String PLACEMENT_ID = "ENTER_PLACEMENT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String adName, - long campaignId, long creativeId, long placementId) throws Exception { - // Retrieve the campaign. - Campaign campaign = reporting.campaigns().get(profileId, campaignId).execute(); - - // Create a click-through URL. - ClickThroughUrl clickThroughUrl = new ClickThroughUrl(); - clickThroughUrl.setDefaultLandingPage(true); - - // Create a creative assignment. - CreativeAssignment creativeAssignment = new CreativeAssignment(); - creativeAssignment.setActive(true); - creativeAssignment.setCreativeId(creativeId); - creativeAssignment.setClickThroughUrl(clickThroughUrl); - - // Create a placement assignment. - PlacementAssignment placementAssignment = new PlacementAssignment(); - placementAssignment.setActive(true); - placementAssignment.setPlacementId(placementId); - - // Create a creative rotation. - CreativeRotation creativeRotation = new CreativeRotation(); - creativeRotation.setCreativeAssignments(ImmutableList.of(creativeAssignment)); - - // Create a delivery schedule. - DeliverySchedule deliverySchedule = new DeliverySchedule(); - deliverySchedule.setImpressionRatio(1L); - deliverySchedule.setPriority("AD_PRIORITY_01"); - - DateTime startDate = new DateTime(new Date()); - DateTime endDate = campaign.getEndDate(); - - // Create a rotation group. - Ad rotationGroup = new Ad(); - rotationGroup.setActive(true); - rotationGroup.setCampaignId(campaignId); - rotationGroup.setCreativeRotation(creativeRotation); - rotationGroup.setDeliverySchedule(deliverySchedule); - rotationGroup.setStartTime(startDate); - rotationGroup.setEndTime(endDate); - rotationGroup.setName(adName); - rotationGroup.setPlacementAssignments(ImmutableList.of(placementAssignment)); - rotationGroup.setType("AD_SERVING_STANDARD_AD"); - - // Insert the rotation group. - Ad result = reporting.ads().insert(profileId, rotationGroup).execute(); - - // Display the new ad ID. - System.out.printf("Ad with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long creativeId = Long.parseLong(CREATIVE_ID); - long placementId = Long.parseLong(PLACEMENT_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, AD_NAME, campaignId, creativeId, placementId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/ads/GetAds.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/ads/GetAds.java deleted file mode 100644 index bcbab04..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/ads/GetAds.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.ads; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Ad; -import com.google.api.services.dfareporting.model.AdsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays the name, ID and advertiser ID for every active ad your DFA user profile - * can see. - */ -public class GetAds { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,ads(advertiserId,id,name)"; - - AdsListResponse result; - String nextPageToken = null; - - do { - // Create and execute the ad list request. - result = reporting.ads().list(profileId).setActive(true).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Ad ad : result.getAds()) { - System.out.printf( - "Ad with ID %d and name \"%s\" is associated with advertiser ID %d.%n", ad.getId(), - ad.getName(), ad.getAdvertiserId()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getAds().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/AssignAdvertisersToAdvertiserGroup.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/AssignAdvertisersToAdvertiserGroup.java deleted file mode 100644 index c346b38..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/AssignAdvertisersToAdvertiserGroup.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Advertiser; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example assigns an advertiser to an advertiser group. - * - * CAUTION: An advertiser that has campaigns associated with it cannot be removed from an - * advertiser group once assigned. - */ -public class AssignAdvertisersToAdvertiserGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String ADVERTISER_GROUP_ID = "INSERT_ADVERTISER_GROUP_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long advertiserGroupId) throws Exception { - // Create the Advertiser and populate with the group ID to patch. - Advertiser advertiser = new Advertiser(); - advertiser.setAdvertiserGroupId(advertiserGroupId); - - // Patch the existing advertiser. - Advertiser result = - reporting.advertisers().patch(profileId, advertiserId, advertiser).execute(); - - // Print out the advertiser and advertiser group ID. - System.out.printf("Advertiser with ID %d was assigned to advertiser group \"%s\".%n", - result.getId(), result.getAdvertiserGroupId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long advertiserGroupId = Long.parseLong(ADVERTISER_GROUP_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, advertiserGroupId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiser.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiser.java deleted file mode 100644 index fb748c1..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiser.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Advertiser; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - - -/** - * This example creates an advertiser in a given DFA account. To get advertisers, see - * GetAdvertisers.java. - */ -public class CreateAdvertiser { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_NAME = "INSERT_ADVERTISER_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String advertiserName) - throws Exception { - // Create the advertiser structure. - Advertiser advertiser = new Advertiser(); - advertiser.setName(advertiserName); - advertiser.setStatus("APPROVED"); - - // Create the advertiser. - Advertiser result = reporting.advertisers().insert(profileId, advertiser).execute(); - - // Display the advertiser ID. - System.out.printf("Advertiser with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, ADVERTISER_NAME); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserGroup.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserGroup.java deleted file mode 100644 index 591212d..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserGroup.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserGroup; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates an advertiser group. To get advertiser groups, see GetAdvertiserGroups.java. - */ -public class CreateAdvertiserGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_GROUP_NAME = "INSERT_ADVERTISER_GROUP_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String advertiserGroupName) - throws Exception { - // Create advertiser group structure. - AdvertiserGroup advertiserGroup = new AdvertiserGroup(); - advertiserGroup.setName(advertiserGroupName); - - // Create advertiser group. - AdvertiserGroup result = - reporting.advertiserGroups().insert(profileId, advertiserGroup).execute(); - - // Display advertiser group ID. - System.out.printf("Advertiser Group with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, ADVERTISER_GROUP_NAME); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserLandingPage.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserLandingPage.java deleted file mode 100644 index dc35f71..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserLandingPage.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates an advertiser landing page. - */ -public class CreateAdvertiserLandingPage { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String LANDING_PAGE_NAME = "INSERT_LANDING_PAGE_NAME_HERE"; - private static final String LANDING_PAGE_URL = "INSERT_LANDING_PAGE_URL_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - String landingPageName, String landingPageUrl) throws Exception { - // Create the landing page structure. - LandingPage landingPage = new LandingPage(); - landingPage.setAdvertiserId(advertiserId); - landingPage.setArchived(false); - landingPage.setName(landingPageName); - landingPage.setUrl(landingPageUrl); - - // Create the landing page - LandingPage result = - reporting.advertiserLandingPages().insert(profileId, landingPage).execute(); - - // Display the landing page ID. - System.out.printf("Advertiser landing page with ID %d and name \"%s\" was created.%n", - result.getId(), result.getName()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long advertiserId = Long.parseLong(ADVERTISER_ID); - - runExample(reporting, profileId, advertiserId, LANDING_PAGE_NAME, LANDING_PAGE_URL); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserGroups.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserGroups.java deleted file mode 100644 index 60d6543..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserGroups.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserGroup; -import com.google.api.services.dfareporting.model.AdvertiserGroupsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all advertiser groups for the specified user profile. - */ -public class GetAdvertiserGroups { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,advertiserGroups(id,name)"; - - // List all advertiser groups - AdvertiserGroupsListResponse result = - reporting.advertiserGroups().list(profileId).setFields(fields).execute(); - - // Display advertiser group names and IDs - if (!result.getAdvertiserGroups().isEmpty()) { - for (AdvertiserGroup group : result.getAdvertiserGroups()) { - System.out.printf("Advertiser Group with ID %d and name \"%s\" was found.%n", - group.getId(), group.getName()); - } - } else { - System.out.print("No advertiser groups found for your criteria."); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserLandingPages.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserLandingPages.java deleted file mode 100644 index 4aec5b7..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserLandingPages.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserLandingPagesListResponse; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all landing pages for a specified advertiser. - */ -public class GetAdvertiserLandingPages { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,landingPages(id,name,url)"; - - AdvertiserLandingPagesListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser landing pages list request. - result = reporting.advertiserLandingPages().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (LandingPage landingPage : result.getLandingPages()) { - System.out.printf( - "Advertiser landing page with ID %d, name \"%s\", and URL %s was found.%n", - landingPage.getId(), landingPage.getName(), landingPage.getUrl()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getLandingPages().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long advertiserId = Long.parseLong(ADVERTISER_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertisers.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertisers.java deleted file mode 100644 index 23b5a48..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertisers.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Advertiser; -import com.google.api.services.dfareporting.model.AdvertisersListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays the name, ID and spotlight configuration ID for every advertiser your DFA - * user profile can see. - */ -public class GetAdvertisers { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,advertisers(id,floodlightConfigurationId,name)"; - - AdvertisersListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser list request. - result = reporting.advertisers().list(profileId).setFields(fields).setPageToken(nextPageToken) - .execute(); - - for (Advertiser advertiser : result.getAdvertisers()) { - System.out.printf("Advertiser with ID %d, name \"%s\", and floodlight configuration ID %d " - + "was found.%n", advertiser.getId(), advertiser.getName(), - advertiser.getFloodlightConfigurationId()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getAdvertisers().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingServiceAccount.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingServiceAccount.java deleted file mode 100644 index 60e2023..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingServiceAccount.java +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.auth; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.DfareportingScopes; -import com.google.api.services.dfareporting.model.UserProfileList; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableSet; -import java.io.FileInputStream; - -/** - * This example demonstrates how to authenticate and make a basic request using a service account. - */ -public class AuthenticateUsingServiceAccount { - private static final String PATH_TO_JSON_FILE = "ENTER_PATH_TO_JSON_FILE_HERE"; - - /** - * An optional Google account email to impersonate. Only applicable to service accounts which have - * enabled domain-wide delegation and wish to make API requests on behalf of an account within - * their domain. Setting this field will not allow you to impersonate a user from a domain you - * don't own (e.g., gmail.com). - */ - private static final String EMAIL_TO_IMPERSONATE = ""; - - // The OAuth 2.0 scopes to request. - private static final ImmutableSet OAUTH_SCOPES = - ImmutableSet.of(DfareportingScopes.DFAREPORTING); - - private static Credential getServiceAccountCredential( - String pathToJsonFile, String emailToImpersonate) throws Exception { - // Generate a credential object from the specified JSON file. - GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(pathToJsonFile)); - - // Update the credential object with appropriate scopes and impersonation info (if applicable). - if (Strings.isNullOrEmpty(emailToImpersonate)) { - credential = credential.createScoped(OAUTH_SCOPES); - } else { - credential = - new GoogleCredential.Builder() - .setTransport(credential.getTransport()) - .setJsonFactory(credential.getJsonFactory()) - .setServiceAccountId(credential.getServiceAccountId()) - .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey()) - .setServiceAccountScopes(OAUTH_SCOPES) - // Set the email of the user you are impersonating (this can be yourself). - .setServiceAccountUser(emailToImpersonate) - .build(); - } - - return credential; - } - - public static void runExample(Dfareporting reporting) throws Exception { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = reporting.userProfiles().list().execute(); - for (int i = 0; i < profiles.getItems().size(); i++) { - System.out.printf("%d) %s%n", i + 1, profiles.getItems().get(i).getUserName()); - } - } - - public static void main(String[] args) throws Exception { - // Build service account credential. - Credential credential = getServiceAccountCredential(PATH_TO_JSON_FILE, EMAIL_TO_IMPERSONATE); - - // Create a Dfareporting client instance. - // - // Note: application name below should be replaced with a value that identifies your - // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion". - Dfareporting reporting = - new Dfareporting.Builder(credential.getTransport(), credential.getJsonFactory(), credential) - .setApplicationName("dfareporting-java-service-acct-sample") - .build(); - - runExample(reporting); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingUserAccount.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingUserAccount.java deleted file mode 100644 index 3bba0e2..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingUserAccount.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.auth; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; -import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; -import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; -import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.util.store.DataStoreFactory; -import com.google.api.client.util.store.FileDataStoreFactory; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.DfareportingScopes; -import com.google.api.services.dfareporting.model.UserProfileList; -import com.google.common.collect.ImmutableSet; -import java.nio.file.Files; -import java.nio.file.Paths; - -/** - * This example demonstrates how to authenticate and make a basic request using a user account, via - * the OAuth 2.0 - * installed application flow. - */ -public class AuthenticateUsingUserAccount { - private static final String PATH_TO_CLIENT_SECRETS = "ENTER_PATH_TO_CLIENT_SECRETS_HERE"; - - // Location where authorization credentials will be cached. - private static final java.io.File DATA_STORE_DIR = - new java.io.File(System.getProperty("user.home"), ".store/dfareporting_auth_sample"); - - // The OAuth 2.0 scopes to request. - private static final ImmutableSet OAUTH_SCOPES = - ImmutableSet.of(DfareportingScopes.DFAREPORTING); - - private static Credential getUserAccountCredential( - String pathToClientSecretsFile, DataStoreFactory dataStoreFactory) throws Exception { - HttpTransport httpTransport = Utils.getDefaultTransport(); - JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); - - // Load the client secrets JSON file. - GoogleClientSecrets clientSecrets = - GoogleClientSecrets.load( - jsonFactory, Files.newBufferedReader(Paths.get(pathToClientSecretsFile), UTF_8)); - - // Set up the authorization code flow. - // - // Note: providing a DataStoreFactory allows auth credentials to be cached, so they survive - // multiple runs of the program. This avoids prompting the user for authorization every time the - // access token expires, by remembering the refresh token. - GoogleAuthorizationCodeFlow flow = - new GoogleAuthorizationCodeFlow.Builder( - httpTransport, jsonFactory, clientSecrets, OAUTH_SCOPES) - .setDataStoreFactory(dataStoreFactory) - .build(); - - // Authorize and persist credentials to the data store. - // - // Note: the "user" value below is used to identify a specific set of credentials in the data - // store. You may provide different values here to persist credentials for multiple users to - // the same data store. - Credential credential = - new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); - - return credential; - } - - public static void runExample(Dfareporting reporting) throws Exception { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = reporting.userProfiles().list().execute(); - for (int i = 0; i < profiles.getItems().size(); i++) { - System.out.printf("%d) %s%n", i + 1, profiles.getItems().get(i).getUserName()); - } - } - - public static void main(String[] args) throws Exception { - // Build installed application credential. - Credential credential = - getUserAccountCredential(PATH_TO_CLIENT_SECRETS, new FileDataStoreFactory(DATA_STORE_DIR)); - - // Create a Dfareporting client instance. - // - // Note: application name below should be replaced with a value that identifies your - // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion". - Dfareporting reporting = - new Dfareporting.Builder(credential.getTransport(), credential.getJsonFactory(), credential) - .setApplicationName("dfareporting-java-installed-app-sample") - .build(); - - runExample(reporting); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaign.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaign.java deleted file mode 100644 index 6e4fdbd..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaign.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.campaigns; - -import com.google.api.client.util.DateTime; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserLandingPagesListResponse; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import com.google.common.collect.ImmutableList; -import java.util.Calendar; - -/** - * This example creates a campaign associated with a given advertiser. To create an advertiser, run - * CreateAdvertiser.java. - */ -public class CreateCampaign { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String campaignName, - long advertiserId) throws Exception { - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(reporting, profileId, advertiserId); - - // Create the campaign structure. - Campaign campaign = new Campaign(); - campaign.setName(campaignName); - campaign.setAdvertiserId(advertiserId); - campaign.setArchived(false); - campaign.setDefaultLandingPageId(defaultLandingPage.getId()); - - // Set the campaign start date. This example uses today's date. - Calendar today = Calendar.getInstance(); - DateTime startDate = new DateTime(true, today.getTimeInMillis(), null); - campaign.setStartDate(startDate); - - // Set the campaign end date. This example uses one month from today's date. - Calendar nextMonth = Calendar.getInstance(); - nextMonth.add(Calendar.MONTH, 1); - DateTime endDate = new DateTime(true, nextMonth.getTimeInMillis(), null); - campaign.setEndDate(endDate); - - // Insert the campaign. - Campaign result = reporting.campaigns().insert(profileId, campaign).execute(); - - // Display the new campaign ID. - System.out.printf("Campaign with ID %d was created.%n", result.getId()); - } - - private static LandingPage getAdvertiserLandingPage(Dfareporting reporting, long profileId, - long advertiserId) throws Exception { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesListResponse landingPages = reporting.advertiserLandingPages() - .list(profileId).setAdvertiserIds(ImmutableList.of(advertiserId)).setMaxResults(1) - .execute(); - - if (landingPages.getLandingPages() == null || landingPages.getLandingPages().isEmpty()) { - throw new IllegalStateException( - "No landing pages found for advertiser with ID " + advertiserId); - } - - return landingPages.getLandingPages().get(0); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CAMPAIGN_NAME, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaignEventTag.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaignEventTag.java deleted file mode 100644 index 1b6d14c..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaignEventTag.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.campaigns; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.EventTag; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates an event tag for the specified campaign. - */ -public class CreateCampaignEventTag { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String EVENT_TAG_NAME = "INSERT_EVENT_TAG_NAME_HERE"; - private static final String EVENT_TAG_URL = "INSERT_EVENT_TAG_URL_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long campaignId, - String eventTagName, String eventTagUrl) throws Exception { - // Create the event tag structure. - EventTag eventTag = new EventTag(); - eventTag.setCampaignId(campaignId); - eventTag.setName(eventTagName); - eventTag.setStatus("ENABLED"); - eventTag.setType("CLICK_THROUGH_EVENT_TAG"); - eventTag.setUrl(eventTagUrl); - - // Insert the campaign. - EventTag result = reporting.eventTags().insert(profileId, eventTag).execute(); - - // Display the new campaign ID. - System.out.printf("Event Tag with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, campaignId, EVENT_TAG_NAME, EVENT_TAG_URL); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/GetCampaigns.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/GetCampaigns.java deleted file mode 100644 index 73f9333..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/campaigns/GetCampaigns.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.campaigns; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.CampaignsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all existing campaigns for the specified user profile. - */ -public class GetCampaigns { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,campaigns(id,name)"; - - CampaignsListResponse campaigns; - String nextPageToken = null; - - do { - // Create and execute the campaigns list request. - campaigns = reporting.campaigns().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Campaign campaign : campaigns.getCampaigns()) { - System.out.printf("Campaign with ID %d and name \"%s\" was found.%n", campaign.getId(), - campaign.getName()); - } - - // Update the next page token. - nextPageToken = campaigns.getNextPageToken(); - } while (!campaigns.getCampaigns().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineMobileConversion.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineMobileConversion.java deleted file mode 100644 index fd900c4..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineMobileConversion.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2016 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertResponse; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example inserts an offline conversion attributed to a mobile device ID, and associated - * with the specified Floodlight activity. To create an activity, run CreateFloodlightActivity.java. - */ -public class InsertOfflineMobileConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CONVERSION_MOBILE_ID = "INSERT_CONVERSION_MOBILE_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long floodlightActivityId, - String mobileDeviceId) throws Exception { - long currentTimeInMilliseconds = System.currentTimeMillis(); - - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - Conversion conversion = new Conversion(); - conversion.setMobileDeviceId(mobileDeviceId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(String.valueOf(currentTimeInMilliseconds)); - conversion.setTimestampMicros(currentTimeInMilliseconds * 1000); - - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.setConversions(ImmutableList.of(conversion)); - - ConversionsBatchInsertResponse response = reporting.conversions() - .batchinsert(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully inserted conversion for mobile device ID %s.%n", - mobileDeviceId); - } else { - System.out.printf("Error(s) inserting conversion for mobile device ID %s:%n", - mobileDeviceId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_MOBILE_ID); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineUserConversion.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineUserConversion.java deleted file mode 100644 index c066e12..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineUserConversion.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2016 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertResponse; -import com.google.api.services.dfareporting.model.EncryptionInfo; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example inserts an offline conversion attributed to an encrypted user ID, and associated - * with the specified Floodlight activity. To create an activity, run CreateFloodlightActivity.java. - */ -public class InsertOfflineUserConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CONVERSION_USER_ID = "INSERT_CONVERSION_USER_ID_HERE"; - private static final String ENCRYPTION_ENTITY_ID = "INSERT_ENCRYPTION_ENTITY_ID_HERE"; - private static final String ENCRYPTION_ENTITY_TYPE = "INSERT_ENCRYPTION_ENTITY_TYPE_HERE"; - private static final String ENCRYPTION_SOURCE = "INSERT_ENCRYPTION_SOURCE_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long floodlightActivityId, - String encryptedUserId, long encryptionEntityId, String encryptionEntityType, - String encryptionSource) throws Exception { - long currentTimeInMilliseconds = System.currentTimeMillis(); - - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - Conversion conversion = new Conversion(); - conversion.setEncryptedUserId(encryptedUserId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(String.valueOf(currentTimeInMilliseconds)); - conversion.setTimestampMicros(currentTimeInMilliseconds * 1000); - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.setEncryptionEntityId(encryptionEntityId); - encryptionInfo.setEncryptionEntityType(encryptionEntityType); - encryptionInfo.setEncryptionSource(encryptionSource); - - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.setConversions(ImmutableList.of(conversion)); - request.setEncryptionInfo(encryptionInfo); - - ConversionsBatchInsertResponse response = reporting.conversions() - .batchinsert(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully inserted conversion for encrypted user ID %s.%n", - encryptedUserId); - } else { - System.out.printf("Error(s) inserting conversion for encrypted user ID %s:%n", - encryptedUserId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long encryptionEntityId = Long.parseLong(ENCRYPTION_ENTITY_ID); - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_USER_ID, encryptionEntityId, - ENCRYPTION_ENTITY_TYPE, ENCRYPTION_SOURCE); - } -} - diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineMobileConversion.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineMobileConversion.java deleted file mode 100644 index 5e799f6..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineMobileConversion.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateResponse; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example updates the quantity and value of a conversion attributed to a mobile device ID. To - * create a conversion attributed to a mobile device ID, run InsertOfflineMobileConversion.java. - */ -public class UpdateOfflineMobileConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Values that identify an existing conversion. - private static final String CONVERSION_MOBILE_ID = "INSERT_CONVERSION_MOBILE_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - private static final String ORDINAL = "INSERT_ORDINAL_VALUE_HERE"; - private static final String TIMESTAMP = "INSERT_TIMESTAMP_IN_MICROSECONDS_HERE"; - - // Values to update for the specified conversion. - private static final String NEW_QUANTITY = "INSERT_NEW_CONVERSION_QUANTITY_HERE"; - private static final String NEW_VALUE = "INSERT_NEW_CONVERSION_VALUE_HERE"; - - public static void runExample( - Dfareporting reporting, long profileId, long floodlightActivityId, String mobileDeviceId, - String ordinal, long timestampMicros, long newQuantity, double newValue) throws Exception { - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - // Create a conversion object populated with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.setMobileDeviceId(mobileDeviceId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(ordinal); - conversion.setTimestampMicros(timestampMicros); - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.setQuantity(newQuantity); - conversion.setValue(newValue); - - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.setConversions(ImmutableList.of(conversion)); - - ConversionsBatchUpdateResponse response = reporting.conversions() - .batchupdate(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully updated conversion for mobile device ID %s.%n", - mobileDeviceId); - } else { - System.out.printf("Error(s) updating conversion for mobile device ID %s:%n", - mobileDeviceId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long newQuantity = Long.parseLong(NEW_QUANTITY); - long profileId = Long.parseLong(USER_PROFILE_ID); - long timestampMicros = Long.parseLong(TIMESTAMP); - - double newValue = Double.parseDouble(NEW_VALUE); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_MOBILE_ID, - ORDINAL, timestampMicros, newQuantity, newValue); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineUserConversion.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineUserConversion.java deleted file mode 100644 index a2a3baf..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineUserConversion.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateResponse; -import com.google.api.services.dfareporting.model.EncryptionInfo; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example updates the quantity and value of a conversion attributed to an encrypted user ID. - * To create a conversion attributed to an encrypted user ID, run InsertOfflineUserConversion.java. - */ -public class UpdateOfflineUserConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Values that identify an existing conversion. - private static final String CONVERSION_USER_ID = "INSERT_CONVERSION_USER_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - private static final String ORDINAL = "INSERT_ORDINAL_VALUE_HERE"; - private static final String TIMESTAMP = "INSERT_TIMESTAMP_IN_MICROSECONDS_HERE"; - - // Values that specify how the existing conversion is encrypted. - private static final String ENCRYPTION_ENTITY_ID = "INSERT_ENCRYPTION_ENTITY_ID_HERE"; - private static final String ENCRYPTION_ENTITY_TYPE = "INSERT_ENCRYPTION_ENTITY_TYPE_HERE"; - private static final String ENCRYPTION_SOURCE = "INSERT_ENCRYPTION_SOURCE_HERE"; - - // Values to update for the specified conversion. - private static final String NEW_QUANTITY = "INSERT_NEW_CONVERSION_QUANTITY_HERE"; - private static final String NEW_VALUE = "INSERT_NEW_CONVERSION_VALUE_HERE"; - - public static void runExample( - Dfareporting reporting, long profileId, long floodlightActivityId, String encryptedUserId, - long encryptionEntityId, String encryptionEntityType, String encryptionSource, String ordinal, - long timestampMicros, long newQuantity, double newValue) throws Exception { - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - // Create a conversion object populated with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.setEncryptedUserId(encryptedUserId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(ordinal); - conversion.setTimestampMicros(timestampMicros); - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.setQuantity(newQuantity); - conversion.setValue(newValue); - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.setEncryptionEntityId(encryptionEntityId); - encryptionInfo.setEncryptionEntityType(encryptionEntityType); - encryptionInfo.setEncryptionSource(encryptionSource); - - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.setConversions(ImmutableList.of(conversion)); - request.setEncryptionInfo(encryptionInfo); - - ConversionsBatchUpdateResponse response = reporting.conversions() - .batchupdate(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully updated conversion for encrypted user ID %s.%n", - encryptedUserId); - } else { - System.out.printf("Error(s) updating conversion for encrypted user ID %s:%n", - encryptedUserId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long encryptionEntityId = Long.parseLong(ENCRYPTION_ENTITY_ID); - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long newQuantity = Long.parseLong(NEW_QUANTITY); - long profileId = Long.parseLong(USER_PROFILE_ID); - long timestampMicros = Long.parseLong(TIMESTAMP); - - double newValue = Double.parseDouble(NEW_VALUE); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_USER_ID, encryptionEntityId, - ENCRYPTION_ENTITY_TYPE, ENCRYPTION_SOURCE, ORDINAL, timestampMicros, newQuantity, newValue); - } -} - diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/AssignCreativeToCampaign.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/AssignCreativeToCampaign.java deleted file mode 100644 index 5b7d3a9..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/AssignCreativeToCampaign.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CampaignCreativeAssociation; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example assigns a given creative to a given campaign. Note that both the creative and - * campaign must be associated with the same advertiser. - */ -public class AssignCreativeToCampaign { - private static final String USER_PROFILE_ID = "INSERT_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String CREATIVE_ID = "INSERT_CREATIVE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long campaignId, - long creativeId) throws Exception { - // Create the campaign creative association structure. - CampaignCreativeAssociation association = new CampaignCreativeAssociation(); - association.setCreativeId(creativeId); - - // Insert the association. - CampaignCreativeAssociation result = reporting - .campaignCreativeAssociations().insert(profileId, campaignId, association) - .execute(); - - // Display a success message. - System.out.printf("Creative with ID %d is now associated with campaign %d.%n", - result.getCreativeId(), campaignId); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long creativeId = Long.parseLong(CREATIVE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, campaignId, creativeId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeField.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeField.java deleted file mode 100644 index 20df281..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeField.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeField; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a creative field associated with a given advertiser. To get an advertiser - * ID, run GetAdvertisers.java. - */ -public class CreateCreativeField { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String CREATIVE_FIELD_NAME = "INSERT_CREATIVE_FIELD_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String creativeFieldName, - long advertiserId) throws Exception { - // Create the creative field. - CreativeField creativeField = new CreativeField(); - creativeField.setName(creativeFieldName); - creativeField.setAdvertiserId(advertiserId); - - // Insert the creative field. - CreativeField result = reporting.creativeFields().insert(profileId, creativeField).execute(); - - // Display the new creative field ID. - System.out.printf("Creative field with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CREATIVE_FIELD_NAME, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeFieldValue.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeFieldValue.java deleted file mode 100644 index d234cd3..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeFieldValue.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeFieldValue; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a creative field value associated with a given creative field. To get the - * creative field ID, run GetCreativeFields.java. - */ -public class CreateCreativeFieldValue { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CREATIVE_FIELD_ID = "INSERT_CREATIVE_FIELD_ID_HERE"; - private static final String CREATIVE_FIELD_VALUE_NAME = "INSERT_CREATIVE_FIELD_VALUE_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, - String creativeFieldValueName, long creativeFieldId) throws Exception { - // Create the creative field value. - CreativeFieldValue creativeFieldValue = new CreativeFieldValue(); - creativeFieldValue.setValue(creativeFieldValueName); - - // Insert the creative field value. - CreativeFieldValue result = reporting.creativeFieldValues() - .insert(profileId, creativeFieldId, creativeFieldValue).execute(); - - // Display the new creative field value ID. - System.out.printf("Creative field value with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long creativeFieldId = Long.parseLong(CREATIVE_FIELD_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CREATIVE_FIELD_VALUE_NAME, creativeFieldId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeGroup.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeGroup.java deleted file mode 100644 index b900b41..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeGroup.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeGroup; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a creative group associated with a given advertiser. To get an advertiser - * ID, run getAdvertisers.java. Valid group numbers are limited to 1 or 2. - */ -public class CreateCreativeGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String CREATIVE_GROUP_NAME = "INSERT_CREATIVE_GROUP_NAME_HERE"; - private static final String GROUP_NUMBER = "INSERT_GROUP_NUMBER_HERE"; - - - public static void runExample(Dfareporting reporting, long profileId, String creativeGroupName, - int groupNumber, long advertiserId) throws Exception { - // Create the creative group. - CreativeGroup creativeGroup = new CreativeGroup(); - creativeGroup.setName(creativeGroupName); - creativeGroup.setGroupNumber(groupNumber); - creativeGroup.setAdvertiserId(advertiserId); - - // Insert the creative group. - CreativeGroup result = reporting.creativeGroups().insert(profileId, creativeGroup).execute(); - - // Display the new creative group ID. - System.out.printf("Creative group with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - int groupNumber = Integer.parseInt(GROUP_NUMBER); - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CREATIVE_GROUP_NAME, groupNumber, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayImageGalleryCreative.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayImageGalleryCreative.java deleted file mode 100644 index dc666a6..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayImageGalleryCreative.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ClickTag; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates a display image gallery creative associated - * with a given advertiser. To get a size ID, run GetSize.java. - */ -public class CreateDisplayImageGalleryCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - // First image asset values. - private static final String IMAGE_ASSET1_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET1_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - // Second image asset values. - private static final String IMAGE_ASSET2_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET2_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long sizeId) throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setAutoAdvanceImages(true); - creative.setName("Test display image gallery creative"); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY_IMAGE_GALLERY"); - - // Upload the first image asset. - CreativeAssetId imageAsset1Id = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET1_NAME, PATH_TO_IMAGE_ASSET1_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset imageAsset1 = - new CreativeAsset().setAssetIdentifier(imageAsset1Id).setRole("PRIMARY"); - - // Upload the second image asset. - CreativeAssetId imageAsset2Id = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET2_NAME, PATH_TO_IMAGE_ASSET2_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset imageAsset2 = - new CreativeAsset().setAssetIdentifier(imageAsset2Id).setRole("PRIMARY"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(imageAsset1, imageAsset2)); - - // Create a click tag for the first image asset. - ClickTag clickTag1 = - new ClickTag().setName(imageAsset1Id.getName()).setEventName(imageAsset1Id.getName()); - - // Create a click tag for the second image asset. - ClickTag clickTag2 = - new ClickTag().setName(imageAsset2Id.getName()).setEventName(imageAsset2Id.getName()); - - // Add the click tags. - creative.setClickTags(ImmutableList.of(clickTag1, clickTag2)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Display image gallery creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, sizeId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayRedirectCreative.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayRedirectCreative.java deleted file mode 100644 index dd9d3bf..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayRedirectCreative.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a display redirect creative associated with a given advertiser. To get a - * size ID, run GetSize.java. - */ -public class CreateDisplayRedirectCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String IMAGE_URL = "INSERT_IMAGE_URL_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - String imageUrl, long sizeId) throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test display redirect creative"); - creative.setRedirectUrl(imageUrl); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY_REDIRECT"); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Display redirect creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, IMAGE_URL, sizeId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateHTML5DisplayCreative.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateHTML5DisplayCreative.java deleted file mode 100644 index 69cd51c..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateHTML5DisplayCreative.java +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserLandingPagesListResponse; -import com.google.api.services.dfareporting.model.ClickTag; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.CreativeClickThroughUrl; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.dfareporting.model.TargetWindow; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an HTML5 display creative associated with a - * given advertiser. To get a size ID, run GetSize.java. - */ -public class CreateHTML5DisplayCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - // HTML5 asset values. - private static final String HTML5_ASSET_NAME = "INSERT_HTML5_ASSET_NAME_HERE"; - private static final String PATH_TO_HTML5_ASSET_FILE = "INSERT_PATH_TO_HTML5_ASSET_FILE_HERE"; - - // Backup image asset values. - private static final String IMAGE_ASSET_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long sizeId) throws Exception { - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(reporting, profileId, advertiserId); - - // Create the creative structure. - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test HTML5 display creative"); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY"); - - // Upload the HTML5 asset. - CreativeAssetId html5AssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, HTML5_ASSET_NAME, PATH_TO_HTML5_ASSET_FILE, "HTML").getAssetIdentifier(); - - CreativeAsset html5Asset = - new CreativeAsset().setAssetIdentifier(html5AssetId).setRole("PRIMARY"); - - // Upload the backup image asset (note: asset type must be set to HTML_IMAGE). - CreativeAssetId imageAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET_NAME, PATH_TO_IMAGE_ASSET_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset backupImageAsset = - new CreativeAsset().setAssetIdentifier(imageAssetId).setRole("BACKUP_IMAGE"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(html5Asset, backupImageAsset)); - - // Configure the backup image. - creative.setBackupImageClickThroughUrl( - new CreativeClickThroughUrl().setLandingPageId(defaultLandingPage.getId())); - creative.setBackupImageReportingLabel("backup"); - creative.setBackupImageTargetWindow(new TargetWindow().setTargetWindowOption("NEW_WINDOW")); - - // Add a click tag. - ClickTag clickTag = - new ClickTag().setName("clickTag").setEventName("exit").setClickThroughUrl( - new CreativeClickThroughUrl().setLandingPageId(defaultLandingPage.getId())); - creative.setClickTags(ImmutableList.of(clickTag)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("HTML5 display creative with ID %d was created.%n", result.getId()); - } - - private static LandingPage getAdvertiserLandingPage(Dfareporting reporting, long profileId, - long advertiserId) throws Exception { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesListResponse landingPages = reporting.advertiserLandingPages() - .list(profileId).setAdvertiserIds(ImmutableList.of(advertiserId)).setMaxResults(1) - .execute(); - - if (landingPages.getLandingPages() == null || landingPages.getLandingPages().isEmpty()) { - throw new IllegalStateException( - "No landing pages found for advertiser with ID " + advertiserId); - } - - return landingPages.getLandingPages().get(0); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, sizeId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateImageDisplayCreative.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateImageDisplayCreative.java deleted file mode 100644 index db77a52..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateImageDisplayCreative.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an image display creative associated with a - * given advertiser. To get a size ID, run GetSize.java. - */ -public class CreateImageDisplayCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - // Image asset values. - private static final String IMAGE_ASSET_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long sizeId) throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test image display creative"); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY"); - - // Upload the image asset. - CreativeAssetId imageAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET_NAME, PATH_TO_IMAGE_ASSET_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset asset = new CreativeAsset().setAssetIdentifier(imageAssetId).setRole("PRIMARY"); - - // Add the creative asset. - creative.setCreativeAssets(ImmutableList.of(asset)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Image display creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, sizeId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamAudioCreative.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamAudioCreative.java deleted file mode 100644 index c3152b9..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamAudioCreative.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an in-stream audio creative associated with a - * given advertiser. - */ -public class CreateInstreamAudioCreative { - private static final String USER_PROFILE_ID = "INSERT_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - // Image asset values. - private static final String AUDIO_ASSET_NAME = "INSERT_AUDIO_ASSET_NAME_HERE"; - private static final String PATH_TO_AUDIO_ASSET_FILE = "INSERT_PATH_TO_AUDIO_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test in-stream audio creative"); - creative.setType("INSTREAM_AUDIO"); - - // Upload the audio asset - CreativeAssetId audioAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, AUDIO_ASSET_NAME, PATH_TO_AUDIO_ASSET_FILE, "AUDIO").getAssetIdentifier(); - - CreativeAsset audioAsset = - new CreativeAsset().setAssetIdentifier(audioAssetId).setRole("PARENT_AUDIO"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(audioAsset)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("In-stream audio creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamVideoCreative.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamVideoCreative.java deleted file mode 100644 index 89a2de5..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamVideoCreative.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an in-stream video creative associated with a - * given advertiser. - */ -public class CreateInstreamVideoCreative { - private static final String USER_PROFILE_ID = "INSERT_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - // Image asset values. - private static final String VIDEO_ASSET_NAME = "INSERT_VIDEO_ASSET_NAME_HERE"; - private static final String PATH_TO_VIDEO_ASSET_FILE = "INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test in-stream video creative"); - creative.setType("INSTREAM_VIDEO"); - - // Upload the video asset - CreativeAssetId videoAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, VIDEO_ASSET_NAME, PATH_TO_VIDEO_ASSET_FILE, "VIDEO").getAssetIdentifier(); - - CreativeAsset videoAsset = - new CreativeAsset().setAssetIdentifier(videoAssetId).setRole("PARENT_VIDEO"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(videoAsset)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("In-stream video creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateTrackingCreative.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateTrackingCreative.java deleted file mode 100644 index b088939..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateTrackingCreative.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a tracking creative associated with a given advertiser. - */ -public class CreateTrackingCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test tracking creative"); - creative.setType("TRACKING_TEXT"); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Tracking creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFieldValues.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFieldValues.java deleted file mode 100644 index 75650fc..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFieldValues.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeFieldValue; -import com.google.api.services.dfareporting.model.CreativeFieldValuesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example retrieves available creative field values for a given string and displays the names - * and IDs. - */ -public class GetCreativeFieldValues { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String CREATIVE_FIELD_ID = "ENTER_CREATIVE_FIELD_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long creativeFieldId) - throws Exception { - CreativeFieldValuesListResponse values; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - values = reporting.creativeFieldValues().list(profileId, creativeFieldId) - .setPageToken(nextPageToken).execute(); - - for (CreativeFieldValue value : values.getCreativeFieldValues()) { - System.out.printf("Found creative field value with ID %d and value \"%s\".%n", - value.getId(), value.getValue()); - } - - // Update the next page token. - nextPageToken = values.getNextPageToken(); - } while (!values.getCreativeFieldValues().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long creativeFieldId = Long.parseLong(CREATIVE_FIELD_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, creativeFieldId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFields.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFields.java deleted file mode 100644 index 471e95e..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFields.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeField; -import com.google.api.services.dfareporting.model.CreativeFieldsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all creative fields. - */ -public class GetCreativeFields { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - CreativeFieldsListResponse fields; - String nextPageToken = null; - - do { - // Create and execute the creative fields list request. - fields = reporting.creativeFields().list(profileId).setPageToken(nextPageToken).execute(); - - for (CreativeField field : fields.getCreativeFields()) { - System.out.printf("Found creative field with ID %d and name \"%s\".%n", field.getId(), - field.getName()); - } - - // Update the next page token. - nextPageToken = fields.getNextPageToken(); - } while (!fields.getCreativeFields().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeGroups.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeGroups.java deleted file mode 100644 index f37bcd4..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeGroups.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeGroup; -import com.google.api.services.dfareporting.model.CreativeGroupsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all creative groups. - */ -public class GetCreativeGroups { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - CreativeGroupsListResponse groups; - String nextPageToken = null; - - do { - // Create and execute the creative groups list request. - groups = reporting.creativeGroups().list(profileId).setPageToken(nextPageToken).execute(); - - for (CreativeGroup group : groups.getCreativeGroups()) { - System.out.printf("Found creative group with ID %d and name \"%s\".%n", group.getId(), - group.getName()); - } - - // Update the next page token. - nextPageToken = groups.getNextPageToken(); - } while (!groups.getCreativeGroups().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreatives.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreatives.java deleted file mode 100644 index 3dd4aef..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreatives.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all existing active creatives for a given advertiser. To get an advertiser ID, - * run GetAdvertisers.java. - */ -public class GetCreatives { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,creatives(id,name,type)"; - - CreativesListResponse groups; - String nextPageToken = null; - - do { - // Create and execute the creatives list request. - groups = reporting.creatives().list(profileId).setActive(true).setAdvertiserId(advertiserId) - .setFields(fields).setPageToken(nextPageToken).execute(); - - for (Creative group : groups.getCreatives()) { - System.out.printf("Found %s creative with ID %d and name \"%s\".%n", group.getType(), - group.getId(), group.getName()); - } - - // Update the next page token. - nextPageToken = groups.getNextPageToken(); - } while (!groups.getCreatives().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/assets/CreativeAssetUtils.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/assets/CreativeAssetUtils.java deleted file mode 100644 index d2feab7..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/creatives/assets/CreativeAssetUtils.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives.assets; - -import com.google.api.client.http.InputStreamContent; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.CreativeAssetMetadata; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.net.FileNameMap; -import java.net.URLConnection; - -/** - * Creative asset utilities used by DFA Reporting and Trafficking API creative examples. - */ -public class CreativeAssetUtils { - - /** - * Uploads a creative asset and associates it with the specified advertiser. - * - * @param reporting An initialized {@link Dfareporting} service object - * @param profileId The current user's profile ID - * @param advertiserId The advertiser to associate this creative asset with - * @param assetName A suggested name for the asset - * @param assetFile The path to the asset file to be uploaded - * @param assetType The CreativeAssetId type of the asset - * @return A {@link CreativeAssetMetadata} populated with the name of the asset after insert. - */ - public static CreativeAssetMetadata uploadAsset(Dfareporting reporting, long profileId, - long advertiserId, String assetName, String assetFile, String assetType) throws Exception { - // Open the asset file. - File file = new File(assetFile); - - // Prepare an input stream. - String contentType = getMimeType(assetFile); - InputStreamContent assetContent = - new InputStreamContent(contentType, new BufferedInputStream(new FileInputStream(file))); - assetContent.setLength(file.length()); - - // Create the creative asset ID and Metadata. - CreativeAssetId assetId = new CreativeAssetId(); - assetId.setName(assetName); - assetId.setType(assetType); - - CreativeAssetMetadata metaData = new CreativeAssetMetadata(); - metaData.setAssetIdentifier(assetId); - - // Insert the creative. - CreativeAssetMetadata result = reporting.creativeAssets() - .insert(profileId, advertiserId, metaData, assetContent).execute(); - - // Display the new asset name. - System.out.printf("Creative asset was saved with name \"%s\".%n", - result.getAssetIdentifier().getName()); - - return result; - } - - /** - * Attempts to determine the MIME type of the specified file. If no type is detected, falls back - * to application/octet-stream. - * - * @param fileName The name of the file to find a MIME type for. - * @return The MIME type to use for uploading this file. - * @see FileNameMap#getContentTypeFor(String) - */ - private static String getMimeType(String fileName) { - FileNameMap fileNameMap = URLConnection.getFileNameMap(); - String mimeType = fileNameMap.getContentTypeFor(fileName); - - if (mimeType != null) { - return mimeType; - } - - return "application/octet-stream"; - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivity.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivity.java deleted file mode 100755 index 7a6dc37..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivity.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a floodlight activity in a given activity group. To create an activity - * group, run CreateFloodlightActivityGroup.java. - */ -public class CreateFloodlightActivity { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ACTIVITY_GROUP_ID = "INSERT_ACTIVITY_GROUP_ID_HERE"; - private static final String ACTIVITY_NAME = "INSERT_ACTIVITY_NAME_HERE"; - private static final String URL = "INSERT_EXPECTED_URL_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String activityName, - String url, long activityGroupId) throws Exception { - // Set floodlight activity structure. - FloodlightActivity activity = new FloodlightActivity(); - activity.setName(activityName); - activity.setCountingMethod("STANDARD_COUNTING"); - activity.setExpectedUrl(url); - activity.setFloodlightActivityGroupId(activityGroupId); - activity.setFloodlightTagType("GLOBAL_SITE_TAG"); - - // Create the floodlight tag activity. - FloodlightActivity result = - reporting.floodlightActivities().insert(profileId, activity).execute(); - - // Display new floodlight activity ID. - if (result != null) { - System.out.printf("Floodlight activity with ID %d was created.%n", result.getId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long activityGroupId = Long.parseLong(ACTIVITY_GROUP_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, ACTIVITY_NAME, URL, activityGroupId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivityGroup.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivityGroup.java deleted file mode 100755 index 9d69dd0..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivityGroup.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivityGroup; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a new activity group for a given floodlight configuration. To get a - * floodlight tag configuration ID, run GetAdvertisers.java. - */ -public class CreateFloodlightActivityGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String GROUP_NAME = "INSERT_GROUP_NAME_HERE"; - private static final String FLOODLIGHT_CONFIGURATION_ID = - "INSERT_FLOODLIGHT_CONFIGURATION_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String groupName, - long floodlightConfigurationId) throws Exception { - // Create the floodlight activity group. - FloodlightActivityGroup floodlightActivityGroup = new FloodlightActivityGroup(); - floodlightActivityGroup.setName(groupName); - floodlightActivityGroup.setFloodlightConfigurationId(floodlightConfigurationId); - floodlightActivityGroup.setType("COUNTER"); - - // Insert the activity group. - FloodlightActivityGroup result = - reporting.floodlightActivityGroups().insert(profileId, floodlightActivityGroup).execute(); - - // Display the new activity group ID. - if (result != null) { - System.out.printf("Activity group with ID %d was created.%n", result.getId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long floodlightConfigurationId = Long.parseLong(FLOODLIGHT_CONFIGURATION_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, GROUP_NAME, floodlightConfigurationId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/DownloadFloodlightTags.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/DownloadFloodlightTags.java deleted file mode 100755 index 0db3f1f..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/DownloadFloodlightTags.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.FloodlightActivities.Generatetag; -import com.google.api.services.dfareporting.model.FloodlightActivitiesGenerateTagResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example downloads activity tags for a given floodlight activity. - */ -public class DownloadFloodlightTags { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ACTIVITY_ID = "ENTER_ACTIVITY_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long activityId) - throws Exception { - // Generate the floodlight activity tag. - Generatetag request = reporting.floodlightActivities().generatetag(profileId); - request.setFloodlightActivityId(activityId); - - FloodlightActivitiesGenerateTagResponse response = request.execute(); - - if (response.getGlobalSiteTagGlobalSnippet() != null) { - // This is a global site tag, display both the global snippet and event snippet. - System.out.printf("Global site tag global snippet:%n%n%s", - response.getGlobalSiteTagGlobalSnippet()); - System.out.printf("%n%nGlobal site tag event snippet:%n%n%s", - response.getFloodlightActivityTag()); - } else { - // This is an image or iframe tag. - System.out.printf("Floodlight activity tag:%n%n%s", response.getFloodlightActivityTag()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long activityId = Long.parseLong(ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, activityId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivities.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivities.java deleted file mode 100644 index a1bdd33..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivities.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivitiesListResponse; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays floodlight activities for a given advertiser. - * - * To create an advertiser, run create_advertiser.py. - */ -public class GetFloodlightActivities { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,floodlightActivities(id,name)"; - - FloodlightActivitiesListResponse activities; - String nextPageToken = null; - - do { - // Create and execute the floodlight activities list request. - activities = reporting.floodlightActivities().list(profileId).setAdvertiserId(advertiserId) - .setFields(fields).setPageToken(nextPageToken).execute(); - - for (FloodlightActivity activity : activities.getFloodlightActivities()) { - System.out.printf("Floodlight activity with ID %d and name \"%s\" was found.%n", - activity.getId(), activity.getName()); - } - - // Update the next page token. - nextPageToken = activities.getNextPageToken(); - } while (!activities.getFloodlightActivities().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivityGroups.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivityGroups.java deleted file mode 100644 index 57a595f..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivityGroups.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivityGroup; -import com.google.api.services.dfareporting.model.FloodlightActivityGroupsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays floodlight activity groups for a given advertiser. - * - * To create an advertiser, run create_advertiser.py. - */ -public class GetFloodlightActivityGroups { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "floodlightActivityGroups(id,name)"; - - // Create and execute the floodlight activity groups list request. - FloodlightActivityGroupsListResponse groups = reporting.floodlightActivityGroups() - .list(profileId).setAdvertiserId(advertiserId).setFields(fields).execute(); - - for (FloodlightActivityGroup group : groups.getFloodlightActivityGroups()) { - System.out.printf("Floodlight activity group with ID %d and name \"%s\" was found.%n", - group.getId(), group.getName()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/CreateReportGuide.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/CreateReportGuide.java deleted file mode 100644 index fb8bcde..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/CreateReportGuide.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.guides; - -import com.google.api.client.util.DateTime; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CompatibleFields; -import com.google.api.services.dfareporting.model.DateRange; -import com.google.api.services.dfareporting.model.Dimension; -import com.google.api.services.dfareporting.model.DimensionValue; -import com.google.api.services.dfareporting.model.DimensionValueList; -import com.google.api.services.dfareporting.model.DimensionValueRequest; -import com.google.api.services.dfareporting.model.Metric; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportCompatibleFields; -import com.google.api.services.dfareporting.model.SortedDimension; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.util.Calendar; -import java.util.List; - -/** - * This example provides an end-to-end example of how to create and configure a standard report. - */ -public class CreateReportGuide { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - // 1. Create a report resource - Report report = createReportResource(); - - // 2. Define the report criteria - defineReportCriteria(report); - - // 3. (optional) Look up compatible fields - findCompatibleFields(reporting, profileId, report); - - // 4. Add dimension filters to the report criteria - addDimensionFilters(reporting, profileId, report); - - // 5. Save the report resource - report = insertReportResource(reporting, profileId, report); - } - - private static Report createReportResource() { - Report report = new Report(); - - // Set the required fields "name" and "type". - report.setName("Example standard report"); - report.setType("STANDARD"); - - // Set optional fields - report.setFileName("example_report"); - report.setFormat("CSV"); - - System.out.printf("Creating %s report resource with name \"%s\".%n", report.getType(), - report.getName()); - - return report; - } - - private static void defineReportCriteria(Report report) throws IOException { - // Define a date range to report on. This example uses explicit start and end dates to mimic - // the "LAST_MONTH" relative date range. - DateRange dateRange = new DateRange(); - dateRange.setEndDate(new DateTime(true, System.currentTimeMillis(), null)); - - Calendar lastMonth = Calendar.getInstance(); - lastMonth.add(Calendar.MONTH, -1); - dateRange.setStartDate(new DateTime(true, lastMonth.getTimeInMillis(), null)); - - // Create a report criteria. - Report.Criteria criteria = new Report.Criteria(); - criteria.setDateRange(dateRange); - criteria.setDimensions(Lists.newArrayList(new SortedDimension().setName("advertiser"))); - criteria.setMetricNames(Lists.newArrayList("clicks", "impressions")); - - // Add the criteria to the report resource. - report.setCriteria(criteria); - - System.out.printf("%nAdded report criteria:%n%s%n", criteria.toPrettyString()); - } - - private static void findCompatibleFields(Dfareporting reporting, long profileId, Report report) - throws IOException { - CompatibleFields fields = reporting.reports().compatibleFields() - .query(profileId, report).execute(); - - ReportCompatibleFields reportFields = fields.getReportCompatibleFields(); - - if (!reportFields.getDimensions().isEmpty()) { - // Add a compatible dimension to the report. - Dimension dimension = reportFields.getDimensions().get(0); - SortedDimension sortedDimension = new SortedDimension().setName(dimension.getName()); - report.getCriteria().getDimensions().add(sortedDimension); - } else if (!reportFields.getMetrics().isEmpty()) { - // Add a compatible metric to the report. - Metric metric = reportFields.getMetrics().get(0); - report.getCriteria().getMetricNames().add(metric.getName()); - } - - System.out.printf("%nUpdated report criteria (with compatible fields):%n%s%n", - report.getCriteria().toPrettyString()); - } - - private static void addDimensionFilters(Dfareporting reporting, long profileId, Report report) - throws IOException { - // Query advertiser dimension values for report run dates. - DimensionValueRequest request = new DimensionValueRequest(); - request.setStartDate(report.getCriteria().getDateRange().getStartDate()); - request.setEndDate(report.getCriteria().getDateRange().getEndDate()); - request.setDimensionName("advertiser"); - - DimensionValueList values = reporting.dimensionValues().query(profileId, request).execute(); - - if (!values.getItems().isEmpty()) { - // Add a value as a filter to the report criteria. - List filters = Lists.newArrayList(values.getItems().get(0)); - report.getCriteria().setDimensionFilters(filters); - } - - System.out.printf("%nUpdated report criteria (with valid dimension filters):%n%s%n", - report.getCriteria()); - } - - private static Report insertReportResource(Dfareporting reporting, long profileId, Report report) - throws IOException { - Report insertedReport = reporting.reports().insert(profileId, report).execute(); - - System.out.printf("%nSuccessfully inserted new report with ID %d.%n", insertedReport.getId()); - return insertedReport; - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/DownloadReportGuide.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/DownloadReportGuide.java deleted file mode 100644 index 6e80b75..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/DownloadReportGuide.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.guides; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.Files.Get; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.FileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.base.Strings; -import com.google.common.io.Files; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * This example provides an end-to-end example of how to find and download a report file. - */ -public class DownloadReportGuide { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "INSERT_REPORT_ID_HERE"; - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - // 1. Find a file to download - File file = findFile(reporting, profileId, reportId); - - if (file != null) { - // 2. (optional) Generate browser URL - generateBrowserUrl(reporting, reportId, file.getId()); - - // 3. Directly download the file - directDownloadFile(reporting, reportId, file.getId()); - } else { - System.out.printf("No file found for profile ID %s and report ID %d.%n", profileId, reportId); - } - } - - private static File findFile(Dfareporting reporting, long profileId, long reportId) - throws IOException { - File target = null; - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - files = reporting.reports().files().list(profileId, reportId).setPageToken(nextPageToken) - .execute(); - - for (File file : files.getItems()) { - if (isTargetFile(file)) { - target = file; - break; - } - } - - // Update the next page token. - nextPageToken = files.getNextPageToken(); - } while (target == null - && !files.getItems().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - - if (target != null) { - System.out.printf("Found file %d with filename \"%s\".%n", target.getId(), - target.getFileName()); - return target; - } - - System.out.printf("Unable to find file for profile ID %d and report ID %d.%n", profileId, - reportId); - return null; - } - - private static boolean isTargetFile(File file) { - // Provide custom validation logic here. - // For example purposes, any file with REPORT_AVAILABLE status is considered valid. - return "REPORT_AVAILABLE".equals(file.getStatus()); - } - - private static String generateBrowserUrl(Dfareporting reporting, long reportId, long fileId) - throws IOException { - File file = reporting.files().get(reportId, fileId).execute(); - String browserUrl = file.getUrls().getBrowserUrl(); - - System.out.printf("File %d has browser URL: %s.%n", file.getId(), browserUrl); - return browserUrl; - } - - private static void directDownloadFile(Dfareporting reporting, long reportId, long fileId) - throws IOException { - // Retrieve the file metadata. - File file = reporting.files().get(reportId, fileId).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // Prepare a local file to download the report contents to. - java.io.File outFile = new java.io.File(Files.createTempDir(), generateFileName(file)); - - // Create a get request. - Get getRequest = reporting.files().get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.getMediaHttpDownloader().setChunkSize(MediaHttpDownloader.MAXIMUM_CHUNK_SIZE); - - // Execute the get request and download the file. - try (OutputStream stream = new FileOutputStream(outFile)) { - getRequest.executeMediaAndDownloadTo(stream); - } - - System.out.printf("File %d downloaded to %s%n", file.getId(), outFile.getAbsolutePath()); - } - } - - private static String generateFileName(File file) { - // If no filename is specified, use the file ID instead. - String fileName = file.getFileName(); - if (Strings.isNullOrEmpty(fileName)) { - fileName = file.getId().toString(); - } - - String extension = "CSV".equals(file.getFormat()) ? ".csv" : ".xls"; - - return fileName + extension; - } -} - diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/FindAndRunReportGuide.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/FindAndRunReportGuide.java deleted file mode 100644 index 9196493..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/guides/FindAndRunReportGuide.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.guides; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.base.Strings; -import java.io.IOException; - -/** - * This example provides an end-to-end example of how to find and run a report. - */ -public class FindAndRunReportGuide { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - // 1. Find a report to run - Report report = findReport(reporting, profileId); - - if (report != null) { - // 2. Run the report - File file = runReport(reporting, profileId, report.getId()); - - // 3. Wait for the report file to be ready - file = waitForReportFile(reporting, report.getId(), file.getId()); - } else { - System.out.printf("No report found for profile ID %d.%n", profileId); - } - } - - private static Report findReport(Dfareporting reporting, long profileId) - throws IOException { - Report target = null; - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the reports list request. - reports = reporting.reports().list(profileId).setPageToken(nextPageToken).execute(); - - for (Report report : reports.getItems()) { - if (isTargetReport(report)) { - target = report; - break; - } - } - - // Update the next page token. - nextPageToken = reports.getNextPageToken(); - } while (target == null - && !reports.getItems().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - - if (target != null) { - System.out.printf("Found report %d with name \"%s\".%n", target.getId(), target.getName()); - return target; - } - - System.out.printf("Unable to find report for profile ID %d.%n", profileId); - return null; - } - - @SuppressWarnings("unused") - private static boolean isTargetReport(Report report) { - // Provide custom validation logic here. - // For example purposes, any report is considered valid. - return true; - } - - private static File runReport(Dfareporting reporting, long profileId, long reportId) - throws IOException { - // Run the report. - File file = reporting.reports().run(profileId, reportId).execute(); - - System.out.printf( - "Running report %d, current file status is %s.%n", reportId, file.getStatus()); - return file; - } - - private static File waitForReportFile(Dfareporting reporting, long reportId, - long fileId) throws IOException, InterruptedException { - BackOff backOff = - new ExponentialBackOff.Builder() - .setInitialIntervalMillis(10 * 1000) // 10 second initial retry - .setMaxIntervalMillis(10 * 60 * 1000) // 10 minute maximum retry - .setMaxElapsedTimeMillis(60 * 60 * 1000) // 1 hour total retry - .build(); - - do { - File file = reporting.files().get(reportId, fileId).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // File has finished processing. - System.out.printf("File status is %s, ready to download.%n", file.getStatus()); - return file; - } else if (!"PROCESSING".equals(file.getStatus())) { - // File failed to process. - System.out.printf("File status is %s, processing failed.", file.getStatus()); - return null; - } - - // The file hasn't finished processing yet, wait before checking again. - long retryInterval = backOff.nextBackOffMillis(); - if (retryInterval == BackOff.STOP) { - System.out.println("File processing deadline exceeded.%n"); - return null; - } - - System.out.printf("File status is %s, sleeping for %dms.%n", file.getStatus(), retryInterval); - Thread.sleep(retryInterval); - } while (true); - } -} - diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetChangeLogsForAdvertiser.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetChangeLogsForAdvertiser.java deleted file mode 100644 index cc277da..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetChangeLogsForAdvertiser.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.misc; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ChangeLog; -import com.google.api.services.dfareporting.model.ChangeLogsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example displays the change logs of a specified advertiser object. - * - * A similar pattern can be applied to get change logs for many other object types. - */ -public class GetChangeLogsForAdvertiser { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,changeLogs(action,fieldName,oldValue,newValue)"; - - ChangeLogsListResponse changeLogs; - String nextPageToken = null; - - do { - // Create and execute the change logs list request - changeLogs = reporting.changeLogs().list(profileId) - .setObjectIds(ImmutableList.of(advertiserId)).setObjectType("OBJECT_ADVERTISER") - .setFields(fields).setPageToken(nextPageToken).execute(); - - for (ChangeLog changeLog : changeLogs.getChangeLogs()) { - System.out.printf("%s: Field \"%s\" from \"%s\" to \"%s\".%n", changeLog.getAction(), - changeLog.getFieldName(), changeLog.getOldValue(), changeLog.getNewValue()); - } - - // Update the next page token. - nextPageToken = changeLogs.getNextPageToken(); - } while (!changeLogs.getChangeLogs().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSites.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSites.java deleted file mode 100755 index fe565a9..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSites.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.misc; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Site; -import com.google.api.services.dfareporting.model.SitesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all existing sites. - */ -public class GetSites { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,sites(id,keyName)"; - - SitesListResponse sites; - String nextPageToken = null; - - do { - // Create and execute the sites list request. - sites = - reporting.sites().list(profileId).setFields(fields).setPageToken(nextPageToken).execute(); - - for (Site site : sites.getSites()) { - System.out.printf("Found site with ID %d and key name \"%s\".%n", site.getId(), - site.getKeyName()); - } - - // Update the next page token. - nextPageToken = sites.getNextPageToken(); - } while (!sites.getSites().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSize.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSize.java deleted file mode 100644 index 0d5e339..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSize.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.misc; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.dfareporting.model.SizesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all sizes for a given width and height. - */ -public class GetSize { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String HEIGHT = "ENTER_HEIGHT_HERE"; - private static final String WIDTH = "ENTER_WIDTH_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, int height, int width) - throws Exception { - // Create and execute the sizes list request. - SizesListResponse sizes = - reporting.sizes().list(profileId).setHeight(height).setWidth(width).execute(); - - for (Size size : sizes.getSizes()) { - System.out.printf("Found size with ID %d.%n", size.getId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - int height = Integer.parseInt(HEIGHT); - int width = Integer.parseInt(WIDTH); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, height, width); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreateContentCategory.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreateContentCategory.java deleted file mode 100644 index aa99d9f..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreateContentCategory.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ContentCategory; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a content category with the given name and description. - */ -public class CreateContentCategory { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CONTENT_CATEGORY_NAME = "INSERT_CONTENT_CATEGORY_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String contentCategoryName) - throws Exception { - // Create the content category. - ContentCategory contentCategory = new ContentCategory(); - contentCategory.setName(contentCategoryName); - - // Insert the content category. - ContentCategory result = - reporting.contentCategories().insert(profileId, contentCategory).execute(); - - // Display the new content category ID. - System.out.printf("Content category with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CONTENT_CATEGORY_NAME); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacement.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacement.java deleted file mode 100644 index cbdadbc..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacement.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.Placement; -import com.google.api.services.dfareporting.model.PricingSchedule; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example creates a placement in a given campaign. Requires a DFA site ID and ID of the - * campaign in which the placement will be created. To create a campaign, run CreateCampaign.java. - * To get a DFA site ID, run GetSite.java. To get a size ID, run GetSize.java. - */ -public class CreatePlacement { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String DFA_SITE_ID = "INSERT_SITE_ID_HERE"; - private static final String PLACEMENT_NAME = "INSERT_PLACEMENT_NAME_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - - public static void runExample(Dfareporting reporting, long profileId, String placementName, - long dfaSiteId, long campaignId, long sizeId) throws Exception { - // Retrieve the campaign. - Campaign campaign = reporting.campaigns().get(profileId, campaignId).execute(); - - // Create the placement. - Placement placement = new Placement(); - placement.setName(placementName); - placement.setCampaignId(campaignId); - placement.setCompatibility("DISPLAY"); - placement.setPaymentSource("PLACEMENT_AGENCY_PAID"); - placement.setSiteId(dfaSiteId); - placement.setTagFormats(ImmutableList.of("PLACEMENT_TAG_STANDARD")); - - // Set the size of the placement. - Size size = new Size(); - size.setId(sizeId); - placement.setSize(size); - - // Set the pricing schedule for the placement. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.setEndDate(campaign.getEndDate()); - pricingSchedule.setPricingType("PRICING_TYPE_CPM"); - pricingSchedule.setStartDate(campaign.getStartDate()); - placement.setPricingSchedule(pricingSchedule); - - // Insert the placement. - Placement result = reporting.placements().insert(profileId, placement).execute(); - - // Display the new placement ID. - System.out.printf("Placement with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long dfaSiteId = Long.parseLong(DFA_SITE_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, PLACEMENT_NAME, dfaSiteId, campaignId, sizeId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementGroup.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementGroup.java deleted file mode 100644 index ed0d046..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementGroup.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.PlacementGroup; -import com.google.api.services.dfareporting.model.PricingSchedule; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a placement group in a given campaign. Requires the DFA site ID and campaign - * ID in which the placement group will be created into. To create a campaign, run - * CreateCampaign.java. To get DFA site ID, run GetSite.java. - */ -public class CreatePlacementGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String DFA_SITE_ID = "INSERT_DFA_SITE_ID_HERE"; - private static final String PLACEMENT_GROUP_NAME = "INSERT_PLACEMENT_GROUP_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long dfaSiteId, - long campaignId, String placementGroupName) throws Exception { - // Retrieve the campaign. - Campaign campaign = reporting.campaigns().get(profileId, campaignId).execute(); - - // Create a pricing schedule. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.setEndDate(campaign.getEndDate()); - pricingSchedule.setPricingType("PRICING_TYPE_CPM"); - pricingSchedule.setStartDate(campaign.getStartDate()); - - // Create the placement group. - PlacementGroup placementGroup = new PlacementGroup(); - placementGroup.setCampaignId(campaignId); - placementGroup.setName(placementGroupName); - placementGroup.setPlacementGroupType("PLACEMENT_PACKAGE"); - placementGroup.setPricingSchedule(pricingSchedule); - placementGroup.setSiteId(dfaSiteId); - - // Insert the placement. - PlacementGroup result = reporting.placementGroups().insert(profileId, placementGroup).execute(); - - // Display the new placement ID. - System.out.printf("Placement group with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long dfaSiteId = Long.parseLong(DFA_SITE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, dfaSiteId, campaignId, PLACEMENT_GROUP_NAME); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementStrategy.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementStrategy.java deleted file mode 100644 index 1aaccca..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementStrategy.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.PlacementStrategy; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a placement strategy with the given name. - */ -public class CreatePlacementStrategy { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String PLACEMENT_STRATEGY_NAME = "INSERT_PLACEMENT_STRATEGY_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, - String placementStrategyName) throws Exception { - // Create the placement strategy. - PlacementStrategy placementStrategy = new PlacementStrategy(); - placementStrategy.setName(placementStrategyName); - - // Insert the placement strategy. - PlacementStrategy result = - reporting.placementStrategies().insert(profileId, placementStrategy).execute(); - - // Display the new placement strategy ID. - System.out.printf("Placement strategy with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, PLACEMENT_STRATEGY_NAME); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/DownloadPlacementTags.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/DownloadPlacementTags.java deleted file mode 100755 index a1991ff..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/DownloadPlacementTags.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.Placements.Generatetags; -import com.google.api.services.dfareporting.model.PlacementTag; -import com.google.api.services.dfareporting.model.PlacementsGenerateTagsResponse; -import com.google.api.services.dfareporting.model.TagData; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; -import java.util.List; - -/** - * This example downloads HTML Tags for a given campaign and placement ID. To create campaigns, run - * CreateCampaign.java. To create placements, run CreatePlacement.java. - */ -public class DownloadPlacementTags { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "ENTER_CAMPAIGN_ID_HERE"; - private static final String PLACEMENT_ID = "ENTER_PLACEMENT_ID_HERE"; - - // The tag formats to generate - private static final ImmutableList TAG_FORMATS = - ImmutableList.of( - "PLACEMENT_TAG_STANDARD", - "PLACEMENT_TAG_IFRAME_JAVASCRIPT", - "PLACEMENT_TAG_INTERNAL_REDIRECT"); - - public static void runExample(Dfareporting reporting, long profileId, long campaignId, - long placementId, List tagFormats) throws Exception { - // Generate the placement activity tags. - Generatetags request = reporting.placements().generatetags(profileId); - request.setCampaignId(campaignId); - request.setTagFormats(tagFormats); - request.setPlacementIds(ImmutableList.of(placementId)); - - PlacementsGenerateTagsResponse response = request.execute(); - - // Display the placement activity tags. - for (PlacementTag tag : response.getPlacementTags()) { - for (TagData tagData : tag.getTagDatas()) { - System.out.printf("%s:%n", tagData.getFormat()); - - if (tagData.getImpressionTag() != null) { - System.out.println(tagData.getImpressionTag()); - } - - if (tagData.getClickTag() != null) { - System.out.println(tagData.getClickTag()); - } - - System.out.printf("%n"); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long placementId = Long.parseLong(PLACEMENT_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, campaignId, placementId, TAG_FORMATS); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetContentCategories.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetContentCategories.java deleted file mode 100644 index 9219aef..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetContentCategories.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ContentCategoriesListResponse; -import com.google.api.services.dfareporting.model.ContentCategory; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all available content categories. - */ -public class GetContentCategories { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,contentCategories(id,name)"; - - ContentCategoriesListResponse categories; - String nextPageToken = null; - - do { - // Create and execute the content categories list request - categories = reporting.contentCategories().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (ContentCategory category : categories.getContentCategories()) { - System.out.printf("Found content category with ID %d and name \"%s\".%n", - category.getId(), category.getName()); - } - - // Update the next page token - nextPageToken = categories.getNextPageToken(); - } while (!categories.getContentCategories().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacementStrategies.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacementStrategies.java deleted file mode 100644 index 4867b1a..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacementStrategies.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.PlacementStrategiesListResponse; -import com.google.api.services.dfareporting.model.PlacementStrategy; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all available placement strategies. - */ -public class GetPlacementStrategies { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,placementStrategies(id,name)"; - - PlacementStrategiesListResponse strategies; - String nextPageToken = null; - - do { - // Create and execute the placement strategies list request. - strategies = reporting.placementStrategies().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (PlacementStrategy strategy : strategies.getPlacementStrategies()) { - System.out.printf("Placement strategy with ID %d and name \"%s\" was found.%n", - strategy.getId(), strategy.getName()); - } - - // Update the next page token. - nextPageToken = strategies.getNextPageToken(); - } while (!strategies.getPlacementStrategies().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacements.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacements.java deleted file mode 100644 index c310859..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacements.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Placement; -import com.google.api.services.dfareporting.model.PlacementsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all available placements. - */ -public class GetPlacements { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,placements(campaignId,id,name)"; - - PlacementsListResponse placements; - String nextPageToken = null; - - do { - // Create and execute the placements list request. - placements = reporting.placements().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Placement placement : placements.getPlacements()) { - System.out.printf( - "Placement with ID %d and name \"%s\" is associated with campaign ID %d.%n", - placement.getId(), placement.getName(), placement.getCampaignId()); - } - - // Update the next page token. - nextPageToken = placements.getNextPageToken(); - } while (!placements.getPlacements().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/CreateRemarketingList.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/CreateRemarketingList.java deleted file mode 100644 index eceb8d0..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/CreateRemarketingList.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ListPopulationClause; -import com.google.api.services.dfareporting.model.ListPopulationRule; -import com.google.api.services.dfareporting.model.ListPopulationTerm; -import com.google.api.services.dfareporting.model.RemarketingList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example creates a remarketing list for a given advertiser and floodlight activity, using a - * custom rule. - * - * Note: this sample assumes that the floodlight activity specified has a U1 custom floodlight - * variable. - */ -public class CreateRemarketingList { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "ENTER_FLOODLIGHT_ACTIVITY_ID_HERE"; - private static final String REMARKETING_LIST_NAME = "ENTER_REMARKETING_LIST_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String remaketingListName, - long advertiserId, long floodlightActivityId) throws Exception { - // Create the remarketing list. - RemarketingList remarketingList = new RemarketingList(); - remarketingList.setActive(true); - remarketingList.setAdvertiserId(advertiserId); - remarketingList.setLifeSpan(30L); // Set the membership lifespan to 30 days. - remarketingList.setName(remaketingListName); - - // Create a list population term. - // This term matches all visitors with a U1 value exactly matching "test_value". - ListPopulationTerm term = new ListPopulationTerm(); - term.setOperator("STRING_EQUALS"); - term.setType("CUSTOM_VARIABLE_TERM"); - term.setValue("test_value"); - term.setVariableName("U1"); - - // Add the term to a list population clause. - ListPopulationClause clause = new ListPopulationClause(); - clause.setTerms(ImmutableList.of(term)); - - // Add the clause to a list population rule. - // This rule will target all visitors who trigger the specified floodlight activity and satisfy - // the custom rule defined in the list population term. - ListPopulationRule rule = new ListPopulationRule(); - rule.setFloodlightActivityId(floodlightActivityId); - rule.setListPopulationClauses(ImmutableList.of(clause)); - remarketingList.setListPopulationRule(rule); - - // Insert the remarketing list. - RemarketingList result = - reporting.remarketingLists().insert(profileId, remarketingList).execute(); - - // Display the new remarketing list ID. - System.out.printf("Remarketing list with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, REMARKETING_LIST_NAME, advertiserId, floodlightActivityId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/GetRemarketingLists.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/GetRemarketingLists.java deleted file mode 100644 index a90baa8..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/GetRemarketingLists.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.RemarketingList; -import com.google.api.services.dfareporting.model.RemarketingListsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all remarketing lists owned by the specified advertiser. - * - * Note: the RemarketingLists resource will only return lists owned by the specified advertiser. To - * see all lists that can be used for targeting ads (including those shared from other accounts or - * advertisers), use the TargetableRemarketingLists resource instead. - */ -public class GetRemarketingLists { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,remarketingLists(accountId,advertiserId,id,name)"; - - RemarketingListsListResponse lists; - String nextPageToken = null; - - do { - // Create and execute the remarketing list request. - lists = reporting.remarketingLists().list(profileId, advertiserId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (RemarketingList list : lists.getRemarketingLists()) { - System.out.printf("Remarketing list with ID %d and name \"%s\" was found.%n", - list.getId(), list.getName()); - } - - // Update the next page token. - nextPageToken = lists.getNextPageToken(); - } while (!lists.getRemarketingLists().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/ShareRemarketingListToAdvertiser.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/ShareRemarketingListToAdvertiser.java deleted file mode 100644 index e76f607..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/ShareRemarketingListToAdvertiser.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.RemarketingListShare; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.base.Joiner; - -import java.util.ArrayList; - -/** - * This example shares an existing remarketing list with the specified advertiser. - */ -public class ShareRemarketingListToAdvertiser { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - private static final String REMARKETING_LIST_ID = "ENTER_REMARKETING_LIST_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long remarketingListId) throws Exception { - // Load the existing share info. - RemarketingListShare share = - reporting.remarketingListShares().get(profileId, remarketingListId).execute(); - - if (share.getSharedAdvertiserIds() == null) { - share.setSharedAdvertiserIds(new ArrayList()); - } - - if (!share.getSharedAdvertiserIds().contains(advertiserId)) { - share.getSharedAdvertiserIds().add(advertiserId); - - // Update the share info with the newly added advertiser ID. - RemarketingListShare result = - reporting.remarketingListShares().update(profileId, share).execute(); - - String sharedAdvertiserIds = Joiner.on(", ").join(result.getSharedAdvertiserIds()); - System.out.printf("Remarketing list with ID %s is now shared to advertiser ID(s): %s.%n", - result.getRemarketingListId(), sharedAdvertiserIds); - } else { - System.out.printf("Remarketing list with ID %d is already shared to advertiser ID %d.%n", - remarketingListId, advertiserId); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - long remarketingListId = Long.parseLong(REMARKETING_LIST_ID); - - runExample(reporting, profileId, advertiserId, remarketingListId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/TargetAdToRemarketingList.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/TargetAdToRemarketingList.java deleted file mode 100644 index c8fb06d..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/remarketing/TargetAdToRemarketingList.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Ad; -import com.google.api.services.dfareporting.model.ListTargetingExpression; -import com.google.api.services.dfareporting.model.TargetableRemarketingList; -import com.google.api.services.dfareporting.model.TargetableRemarketingListsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example targets an ad to a remarketing list. - * - * The first targetable remarketing list, either owned by or shared to the ad's advertiser, will be - * used. To create a remarketing list, see CreateRemarketingList.java. To share a remarketing list - * with the ad's advertiser, see ShareRemarketingListToAdvertiser.java. - */ -public class TargetAdToRemarketingList { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String AD_ID = "ENTER_AD_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long adId) - throws Exception { - Ad ad = reporting.ads().get(profileId, adId).execute(); - - TargetableRemarketingListsListResponse lists = reporting.targetableRemarketingLists() - .list(profileId, ad.getAdvertiserId()).setMaxResults(1).execute(); - - if (!lists.getTargetableRemarketingLists().isEmpty()) { - // Select the first targetable remarketing list that was returned. - TargetableRemarketingList list = lists.getTargetableRemarketingLists().get(0); - - // Create a list targeting expression. - ListTargetingExpression expression = new ListTargetingExpression(); - expression.setExpression(list.getId().toString()); - - // Update the ad. - ad.setRemarketingListExpression(expression); - Ad result = reporting.ads().update(profileId, ad).execute(); - - System.out.printf("Ad with ID %d updated to use remarketing list expression: \"%s\".%n", - result.getId(), result.getRemarketingListExpression().getExpression()); - } else { - System.out.printf("No targetable remarketing lists found for ad with ID %d", adId); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long adId = Long.parseLong(AD_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, adId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/CreateReport.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/CreateReport.java deleted file mode 100644 index 71f79b4..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/CreateReport.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.DateRange; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.Report.Criteria; -import com.google.api.services.dfareporting.model.SortedDimension; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example illustrates how to create a report. - */ -public class CreateReport { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_NAME = "INSERT_REPORT_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String reportName) - throws Exception { - // Create a date range to report on. - DateRange dateRange = new DateRange(); - dateRange.setRelativeDateRange("YESTERDAY"); - - // Create a dimension to report on. - SortedDimension dimension = new SortedDimension(); - dimension.setName("campaign"); - - // Create the criteria for the report. - Criteria criteria = new Criteria(); - criteria.setDateRange(dateRange); - criteria.setDimensions(ImmutableList.of(dimension)); - criteria.setMetricNames(ImmutableList.of("clicks")); - - // Create the report. - Report report = new Report(); - report.setCriteria(criteria); - report.setName(reportName); - report.setType("STANDARD"); - - // Insert the report. - Report result = reporting.reports().insert(profileId, report).execute(); - - // Display the new report ID. - System.out.printf("Standard report with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, REPORT_NAME); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/DeleteReport.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/DeleteReport.java deleted file mode 100644 index dfc21d5..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/DeleteReport.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to delete a report. - */ -public class DeleteReport { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "INSERT_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Delete the report. - reporting.reports().delete(profileId, reportId).execute(); - - // Display the new report ID. - System.out.printf("Report with ID %d was successfully deleted.%n", reportId); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/DownloadFile.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/DownloadFile.java deleted file mode 100644 index 63c8a7d..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/DownloadFile.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.Files.Get; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import com.google.common.base.Strings; -import com.google.common.io.Files; -import java.io.FileOutputStream; -import java.io.OutputStream; - -/** - * This example illustrates how to download a file. - */ -public class DownloadFile { - private static final String FILE_ID = "ENTER_FILE_ID_HERE"; - private static final String REPORT_ID = "ENTER_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long reportId, long fileId) - throws Exception { - // Retrieve the file metadata. - File file = reporting.files().get(reportId, fileId).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // Prepare a local file to download the report contents to. - java.io.File outFile = new java.io.File(Files.createTempDir(), generateFileName(file)); - - // Create a get request. - Get getRequest = reporting.files().get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.getMediaHttpDownloader().setChunkSize(MediaHttpDownloader.MAXIMUM_CHUNK_SIZE); - - // Execute the get request and download the file. - try (OutputStream stream = new FileOutputStream(outFile)) { - getRequest.executeMediaAndDownloadTo(stream); - } - - System.out.printf("File %d downloaded to %s%n", file.getId(), outFile.getAbsolutePath()); - } - } - - private static String generateFileName(File file) { - // If no filename is specified, use the file ID instead. - String fileName = file.getFileName(); - if (Strings.isNullOrEmpty(fileName)) { - fileName = file.getId().toString(); - } - - String extension = "CSV".equals(file.getFormat()) ? ".csv" : ".xls"; - - return fileName + extension; - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long fileId = Long.parseLong(FILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, reportId, fileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetCompatibleFields.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetCompatibleFields.java deleted file mode 100644 index e6db886..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetCompatibleFields.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CompatibleFields; -import com.google.api.services.dfareporting.model.Dimension; -import com.google.api.services.dfareporting.model.Metric; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportCompatibleFields; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import java.util.List; - -/** - * This example illustrates how to get the compatible fields for a standard report. - */ -public class GetCompatibleFields { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "ENTER_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Retrieve the specified report. - Report report = reporting.reports().get(profileId, reportId).execute(); - - // Look up the compatible fields for the report. - CompatibleFields fields = - reporting.reports().compatibleFields().query(profileId, report).execute(); - - // Display the compatible fields, assuming this is a standard report. - ReportCompatibleFields reportFields = fields.getReportCompatibleFields(); - - System.out.println("Compatible dimensions:"); - printDimensionNames(reportFields.getDimensions()); - - System.out.printf("%nCompatible metrics:%n"); - printMetricNames(reportFields.getMetrics()); - - System.out.printf("%nCompatible dimension filters:%n"); - printDimensionNames(reportFields.getDimensionFilters()); - - System.out.printf("%nCompatible pivoted activity metrics:%n"); - printMetricNames(reportFields.getPivotedActivityMetrics()); - } - - private static void printDimensionNames(List dimensions) { - for (Dimension dimension : dimensions) { - System.out.println(dimension.getName()); - } - } - - private static void printMetricNames(List metrics) { - for (Metric metric : metrics) { - System.out.println(metric.getName()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetDimensionValues.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetDimensionValues.java deleted file mode 100644 index fa35d90..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetDimensionValues.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.DateTime; -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.DimensionValue; -import com.google.api.services.dfareporting.model.DimensionValueList; -import com.google.api.services.dfareporting.model.DimensionValueRequest; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import java.util.Calendar; - -/** - * This example illustrates how to get all dimension values for a dimension. - */ -public class GetDimensionValues { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(id,value)"; - - // Construct the dimension value request. - DimensionValueRequest request = new DimensionValueRequest(); - request.setDimensionName("advertiser"); - - // Set the date range from 1 year ago until today. - Calendar today = Calendar.getInstance(); - Calendar lastYear = Calendar.getInstance(); - lastYear.add(Calendar.YEAR, -1); - - request.setStartDate(new DateTime(true, lastYear.getTimeInMillis(), null)); - request.setEndDate(new DateTime(true, today.getTimeInMillis(), null)); - - DimensionValueList values; - String nextPageToken = null; - - do { - // Create and execute the dimension value query request. - values = reporting.dimensionValues().query(profileId, request).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (DimensionValue value : values.getItems()) { - System.out.printf("Dimension value with ID %s and value \"%s\" was found.%n", - value.getId(), value.getValue()); - } - - // Update the next page token. - nextPageToken = values.getNextPageToken(); - } while (!values.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetFiles.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetFiles.java deleted file mode 100644 index 85155f8..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetFiles.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.FileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all the files for a profile. - */ -public class GetFiles { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - files = - reporting.files().list(profileId).setFields(fields).setPageToken(nextPageToken).execute(); - - for (File file : files.getItems()) { - System.out.printf("Report file with ID %d and file name \"%s\" has status \"%s\".%n", - file.getId(), file.getFileName(), file.getStatus()); - } - - // Update the next page token. - nextPageToken = files.getNextPageToken(); - } while (!files.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReportFiles.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReportFiles.java deleted file mode 100644 index 9cdced7..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReportFiles.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.FileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all the files for a report. - */ -public class GetReportFiles { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "ENTER_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the report files list request. - files = reporting.reports().files().list(profileId, reportId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (File file : files.getItems()) { - System.out.printf("Report file with ID %d and file name \"%s\" has status \"%s\".%n", - file.getId(), file.getFileName(), file.getStatus()); - } - - // Update the next page token. - nextPageToken = files.getNextPageToken(); - } while (!files.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReports.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReports.java deleted file mode 100644 index 5bb6cd7..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReports.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all reports. - */ -public class GetReports { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(id,name,type)"; - - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the report list request. - reports = reporting.reports().list(profileId).setFields(fields).setPageToken(nextPageToken) - .execute(); - - for (Report report : reports.getItems()) { - System.out.printf("%s report with ID %d and name \"%s\" was found.%n", report.getType(), - report.getId(), report.getName()); - } - - // Update the next page token. - nextPageToken = reports.getNextPageToken(); - } while (!reports.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/RunReport.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/RunReport.java deleted file mode 100644 index c627916..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/reports/RunReport.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to run a report. - */ -public class RunReport { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "INSERT_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Run the report. - File file = reporting.reports().run(profileId, reportId).execute(); - System.out.printf("File with ID %d has been created.%n", file.getId()); - - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve request quota. - BackOff backOff = - new ExponentialBackOff.Builder() - .setInitialIntervalMillis(10 * 1000) // 10 second initial retry - .setMaxIntervalMillis(10 * 60 * 1000) // 10 minute maximum retry - .setMaxElapsedTimeMillis(60 * 60 * 1000) // 1 hour total retry - .build(); - - do { - file = reporting.files().get(file.getReportId(), file.getId()).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // File has finished processing. - System.out.printf("File status is %s, ready to download.%n", file.getStatus()); - return; - } else if (!"PROCESSING".equals(file.getStatus())) { - // File failed to process. - System.out.printf("File status is %s, processing failed.", file.getStatus()); - return; - } - - // The file hasn't finished processing yet, wait before checking again. - long retryInterval = backOff.nextBackOffMillis(); - if (retryInterval == BackOff.STOP) { - System.out.println("File processing deadline exceeded.%n"); - return; - } - - System.out.printf("File status is %s, sleeping for %dms.%n", file.getStatus(), retryInterval); - Thread.sleep(retryInterval); - } while (true); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/CreateSubaccount.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/CreateSubaccount.java deleted file mode 100644 index 6b70566..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/CreateSubaccount.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.subaccounts; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Subaccount; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -import java.util.List; - -/** - * This example creates a subaccount in a given DoubleClick Campaign Manager account. To get the - * available permissions, run GetSubaccountPermissions.java. - */ -public class CreateSubaccount { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ACCOUNT_ID = "INSERT_ACCOUNT_ID_HERE"; - private static final String PERMISSION_ONE = "INSERT_FIRST_PERMISSION_ID_HERE"; - private static final String PERMISSION_TWO = "INSERT_SECOND_PERMISSION_ID_HERE"; - private static final String SUBACCOUNT_NAME = "INSERT_SUBACCOUNT_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String subaccountName, - long accountId, long permissionOneId, long permissionTwoId) throws Exception { - // Create subaccount structure. - Subaccount subaccount = new Subaccount(); - subaccount.setName(subaccountName); - subaccount.setAccountId(accountId); - - // Create a collection of all permissions assigned to this subaccount and add it to the - // subaccount structure. To get list of available permissions, run GetUserRolePermissions.java. - List availablePermissionIds = ImmutableList.of(permissionOneId, permissionTwoId); - subaccount.setAvailablePermissionIds(availablePermissionIds); - - // Create subaccount. - Subaccount result = reporting.subaccounts().insert(profileId, subaccount).execute(); - - // Display subaccount ID. - System.out.printf("Subaccount with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long accountId = Long.parseLong(ACCOUNT_ID); - long permissionOneId = Long.parseLong(PERMISSION_ONE); - long permissionTwoId = Long.parseLong(PERMISSION_TWO); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, SUBACCOUNT_NAME, accountId, permissionOneId, permissionTwoId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccountPermissions.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccountPermissions.java deleted file mode 100644 index 8551837..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccountPermissions.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.subaccounts; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Subaccount; -import com.google.api.services.dfareporting.model.UserRolePermission; -import com.google.api.services.dfareporting.model.UserRolePermissionsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all of the available user role permissions for a specified - * subaccount. - * - * To get a subaccount ID, run GetSubaccounts.java. - */ -public class GetSubaccountPermissions { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String SUBACCOUNT_ID = "ENTER_SUBACCOUNT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long subaccountId) - throws Exception { - // Limit the fields returned. - String fields = "userRolePermissions(id,name)"; - - // Retrieve the subaccount. - Subaccount subaccount = reporting.subaccounts().get(profileId, subaccountId).execute(); - - // Retrieve the subaccount permissions. - UserRolePermissionsListResponse permissions = reporting.userRolePermissions().list(profileId) - .setIds(subaccount.getAvailablePermissionIds()).setFields(fields).execute(); - - // Display the subaccount permissions. - for (UserRolePermission permission : permissions.getUserRolePermissions()) { - System.out.printf("User role permission with ID %d and name \"%s\" was found.%n", - permission.getId(), permission.getName()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long subaccountId = Long.parseLong(SUBACCOUNT_ID); - - runExample(reporting, profileId, subaccountId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccounts.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccounts.java deleted file mode 100644 index 7d29d7b..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccounts.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.subaccounts; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Subaccount; -import com.google.api.services.dfareporting.model.SubaccountsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all subaccounts. - * - * Note that the permissions assigned to a subaccount are not returned in a human-readable format - * with this example. Run GetSubaccountPermissions.java to see what permissions are available on a - * subaccount. - */ -public class GetSubaccounts { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,subaccounts(id,name)"; - - SubaccountsListResponse subaccounts; - String nextPageToken = null; - - do { - // Create and execute the subaccounts list request. - subaccounts = reporting.subaccounts().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Subaccount subaccount : subaccounts.getSubaccounts()) { - System.out.printf("Subaccount with ID %d and name \"%s\" was found.%n", subaccount.getId(), - subaccount.getName()); - } - - // Update the next page token. - nextPageToken = subaccounts.getNextPageToken(); - } while (!subaccounts.getSubaccounts().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/ConfigureDynamicAssetSelection.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/ConfigureDynamicAssetSelection.java deleted file mode 100644 index ae1e7bd..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/ConfigureDynamicAssetSelection.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.targeting; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetMetadata; -import com.google.api.services.dfareporting.model.CreativeAssetSelection; -import com.google.api.services.dfareporting.model.Rule; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; - -import java.util.ArrayList; - -/** - * This example uploads a new video asset to an existing in-stream video creative and configures - * dynamic asset selection, using a specified targeting template. To get an in-stream video - * creative, run CreateInstreamVideoCreative.java. To get a targeting template, run - * CreateTargetingTemplate.java. - */ -public class ConfigureDynamicAssetSelection { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String INSTREAM_VIDEO_CREATIVE_ID = "INSERT_INSTREAM_VIDEO_ASSET_ID_HERE"; - private static final String TARGETING_TEMPLATE_ID = "INSERT_TARGETING_TEMPLATE_ID_HERE"; - - // Video asset values - private static final String VIDEO_ASSET_NAME = "INSERT_VIDEO_ASSET_NAME_HERE"; - private static final String PATH_TO_VIDEO_ASSET_FILE = "INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long creativeId, - long templateId, String videoAssetName, String pathToVideoAsset) throws Exception { - // Retrieve the specified creative. - Creative creative = reporting.creatives().get(profileId, creativeId).execute(); - if (creative == null || !"INSTREAM_VIDEO".equals(creative.getType())) { - System.out.println("Invalid creative specified."); - return; - } - - CreativeAssetSelection selection = creative.getCreativeAssetSelection(); - if (!creative.getDynamicAssetSelection()) { - // Locate an existing video asset to use as a default. - // This example uses the first PARENT_VIDEO asset found. - long defaultVideoAssetId = findDefaultVideoAssetId(creative); - if (defaultVideoAssetId < 0) { - System.out.println("Default video asset could not be found."); - return; - } - - // Create a new selection using the existing asset as a default. - selection = new CreativeAssetSelection(); - selection.setDefaultAssetId(defaultVideoAssetId); - selection.setRules(new ArrayList()); - - // Enable dynamic asset selection for the creative. - creative.setDynamicAssetSelection(true); - creative.setCreativeAssetSelection(selection); - } - - // Upload the new video asset and add it to the creative. - CreativeAssetMetadata videoAssetMetadata = CreativeAssetUtils.uploadAsset(reporting, profileId, - creative.getAdvertiserId(), videoAssetName, pathToVideoAsset, "VIDEO"); - creative.getCreativeAssets().add(new CreativeAsset() - .setAssetIdentifier(videoAssetMetadata.getAssetIdentifier()).setRole("PARENT_VIDEO")); - - // Create a rule targeting the new video asset and add it to the selection. - Rule rule = new Rule(); - rule.setAssetId(videoAssetMetadata.getId()); - rule.setName("Test rule for asset " + videoAssetMetadata.getId()); - rule.setTargetingTemplateId(templateId); - selection.getRules().add(rule); - - // Update the creative. - Creative result = reporting.creatives().update(profileId, creative).execute(); - System.out.printf("Dynamic asset selection enabled for creative with ID %d.%n", - result.getId()); - } - - private static long findDefaultVideoAssetId(Creative creative) { - for (CreativeAsset asset : creative.getCreativeAssets()) { - if ("PARENT_VIDEO".equals(asset.getRole())) { - return asset.getId(); - } - } - - return -1; - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long creativeId = Long.parseLong(INSTREAM_VIDEO_CREATIVE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - long templateId = Long.parseLong(TARGETING_TEMPLATE_ID); - - runExample(reporting, profileId, creativeId, templateId, VIDEO_ASSET_NAME, - PATH_TO_VIDEO_ASSET_FILE); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/CreateTargetingTemplate.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/CreateTargetingTemplate.java deleted file mode 100644 index 105c9ea..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/CreateTargetingTemplate.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.targeting; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.DayPartTargeting; -import com.google.api.services.dfareporting.model.TargetingTemplate; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example creates a basic targeting template associated with a given advertiser. To get an - * advertiser ID, run GetAdvertisers.java. - */ -public class CreateTargetingTemplate { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String TARGETING_TEMPLATE_NAME = "INSERT_TARGETING_TEMPLATE_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String templateName, - long advertiserId) throws Exception { - // Create the targeting template. - TargetingTemplate template = new TargetingTemplate(); - template.setAdvertiserId(advertiserId); - template.setName(templateName); - - // Configure the template to serve ads on Monday, Wednesday, and Friday from 9-10am and 3-5pm. - DayPartTargeting dayTargeting = new DayPartTargeting(); - dayTargeting.setDaysOfWeek(ImmutableList.of("MONDAY", "WEDNESDAY", "FRIDAY")); - dayTargeting.setHoursOfDay(ImmutableList.of(9, 15, 16)); - dayTargeting.setUserLocalTime(true); - template.setDayPartTargeting(dayTargeting); - - // Insert the targeting template. - TargetingTemplate result = - reporting.targetingTemplates().insert(profileId, template).execute(); - - // Display the new targeting template ID. - System.out.printf("Targeting template with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, TARGETING_TEMPLATE_NAME, advertiserId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/GetTargetingTemplates.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/GetTargetingTemplates.java deleted file mode 100644 index ba1bdf8..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/targeting/GetTargetingTemplates.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2016 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.targeting; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.TargetingTemplate; -import com.google.api.services.dfareporting.model.TargetingTemplatesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays the name, ID and advertiser ID for every targeting template your DCM user - * profile can see. - */ -public class GetTargetingTemplates { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,targetingTemplates(advertiserId,id,name)"; - - TargetingTemplatesListResponse result; - String nextPageToken = null; - - do { - // Create and execute the targeting templates list request. - result = reporting.targetingTemplates().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (TargetingTemplate template : result.getTargetingTemplates()) { - System.out.printf( - "Targeting template with ID %d and name \"%s\" is associated with advertiser ID %d.%n", - template.getId(), template.getName(), template.getAdvertiserId()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getTargetingTemplates().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userprofiles/GetUserProfiles.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userprofiles/GetUserProfiles.java deleted file mode 100644 index 114dc48..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userprofiles/GetUserProfiles.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.userprofiles; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.UserProfile; -import com.google.api.services.dfareporting.model.UserProfileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all user profiles. - */ -public class GetUserProfiles { - public static void runExample(Dfareporting reporting) throws Exception { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = reporting.userProfiles().list().execute(); - for (UserProfile profile : profiles.getItems()) { - System.out.printf("User profile with ID %d and name \"%s\" was found for account %d.%n", - profile.getProfileId(), profile.getUserName(), profile.getAccountId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - runExample(reporting); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userroles/CreateUserRole.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userroles/CreateUserRole.java deleted file mode 100644 index 8baaa1f..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userroles/CreateUserRole.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.userroles; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.UserRole; -import com.google.api.services.dfareporting.model.UserRolePermission; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -import java.util.List; - -/** - * This example creates a user role in a given DoubleClick Campaign Manager subaccount. To get the - * subaccount ID, run GetSubaccounts.java. To get the available permissions, run - * GetUserRolePermissions.java. To get the parent user role ID, run GetUserRoles.java. - */ -public class CreateUserRole { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String PARENT_USER_ROLE_ID = "INSERT_PARENT_USER_ROLE_ID_HERE"; - private static final String PERMISSION_ID_ONE = "INSERT_FIRST_PERMISSION_ID_HERE"; - private static final String PERMISSION_ID_TWO = "INSERT_SECOND_PERMISSION_ID_HERE"; - private static final String SUBACCOUNT_ID = "INSERT_SUBACCOUNT_ID_HERE"; - private static final String USER_ROLE_NAME = "INSERT_USER_ROLE_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String userRoleName, - long subaccountId, long parentUserRoleId, long permission1Id, long permission2Id) - throws Exception { - // Create user role structure. - UserRole userRole = new UserRole(); - userRole.setName(userRoleName); - userRole.setSubaccountId(subaccountId); - userRole.setParentUserRoleId(parentUserRoleId); - - // Create a permission object to represent each permission this user role - // has. - UserRolePermission permission1 = new UserRolePermission(); - permission1.setId(permission1Id); - UserRolePermission permission2 = new UserRolePermission(); - permission2.setId(permission2Id); - List permissions = ImmutableList.of(permission1, permission2); - - // Add the permissions to the user role. - userRole.setPermissions(permissions); - - // Create user role. - UserRole result = reporting.userRoles().insert(profileId, userRole).execute(); - - // Display user role ID. - System.out.printf("User role with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long parentUserRoleId = Long.parseLong(PARENT_USER_ROLE_ID); - long permission1Id = Long.parseLong(PERMISSION_ID_ONE); - long permission2Id = Long.parseLong(PERMISSION_ID_TWO); - long profileId = Long.parseLong(USER_PROFILE_ID); - long subaccountId = Long.parseLong(SUBACCOUNT_ID); - - runExample(reporting, profileId, USER_ROLE_NAME, subaccountId, parentUserRoleId, permission1Id, - permission2Id); - } -} diff --git a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userroles/GetUserRoles.java b/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userroles/GetUserRoles.java deleted file mode 100755 index cdb0550..0000000 --- a/java/v3.4/src/main/java/com/google/api/services/samples/dfareporting/userroles/GetUserRoles.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.userroles; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.UserRole; -import com.google.api.services.dfareporting.model.UserRolesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all user roles. - * - * The output is limited to include only ID, name, account ID and subaccount ID. - */ -public class GetUserRoles { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,userRoles(accountId,id,name,subaccountId)"; - - UserRolesListResponse roles; - String nextPageToken = null; - - do { - // Create and execute the user roles list request. - roles = reporting.userRoles().list(profileId).setFields(fields).setPageToken(nextPageToken) - .execute(); - - for (UserRole role : roles.getUserRoles()) { - System.out.printf("User role with ID %d and name \"%s\" was found.%n", role.getId(), - role.getName()); - } - - // Update the next page token. - nextPageToken = roles.getNextPageToken(); - } while (!roles.getUserRoles().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/README.md b/java/v3.5/README.md deleted file mode 100644 index a0a7c32..0000000 --- a/java/v3.5/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# DCM/DFA Reporting and Trafficking API Java Samples - -This is a collection of samples written in Java which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - -Please make sure that you're running Java 7+ and have maven installed. - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Set up your environment ## -### Via the command line ### - -1. Execute the following command: - - ```Batchfile - $ mvn compile - ``` - -### Via Eclipse ### - -1. Setup Eclipse preferences: - 1. Window > Preferences .. (or on Mac, Eclipse > Preferences) - 2. Select Maven - 3. Select "Download Artifact Sources" - 4. Select "Download Artifact JavaDoc" -2. Import the sample project - 1. File > Import... - 2. Select General > Existing Project into Workspace and click "Next" - 3. Click "Browse" next to "Select root directory", find the sample directory and click "Next" - 4. Click "Finish" - -## Running the Examples - -Once you've checked out the code: - -1. Open a sample and fill in any prerequisite values. Required values will be declared as constants near the top of the file. - -2. Run the sample - - 1. Via eclipse, right-click on the project and select Run As > Java Application - -3. Complete the authorization steps on your browser - -4. Examine the console output, be inspired and start hacking an amazing new app! diff --git a/java/v3.5/logging.properties b/java/v3.5/logging.properties deleted file mode 100644 index 08656ce..0000000 --- a/java/v3.5/logging.properties +++ /dev/null @@ -1,10 +0,0 @@ -# Properties file which configures the operation of the JDK logging facility. -# The system will look for this config file to be specified as a system property: -# -Djava.util.logging.config.file=${project_loc:dfareporting-java-sample}/logging.properties - -# Set up the console handler (uncomment "level" to show more fine-grained messages) -handlers = java.util.logging.ConsoleHandler -#java.util.logging.ConsoleHandler.level = CONFIG - -# Set up logging of HTTP requests and responses (uncomment "level" to show) -#com.google.api.client.http.level = CONFIG diff --git a/java/v3.5/pom.xml b/java/v3.5/pom.xml deleted file mode 100644 index 816a494..0000000 --- a/java/v3.5/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - 4.0.0 - com.google.apis-samples - dfareporting-java-sample - 1.0.0 - Samples for the DFA Reporting and Trafficking API using JSON and OAuth 2.0 - - 2015 - - - 2.0.9 - - - - - jimper - Jonathon Imperiosi - jimper@users.noreply.github.com - Google - http://www.google.com - - owner - developer - - -5 - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - org.codehaus.mojo - exec-maven-plugin - 1.1 - - - - java - - - - - - org.codehaus.mojo - findbugs-maven-plugin - 2.3.2 - - false - - - - - check - - - - - - ${project.artifactId}-${project.version} - - - - com.google.apis - google-api-services-dfareporting - v3.5-rev20210524-1.31.0 - - - com.google.guava - guava-jdk5 - - - - - com.google.http-client - google-http-client-jackson2 - ${project.http.version} - - - com.google.apis - google-api-services-oauth2 - v1-rev155-1.25.0 - - - com.google.oauth-client - google-oauth-client-jetty - ${project.oauth.version} - - - com.google.guava - guava - [30.0-jre,) - - - - 1.39.2 - 1.28.0 - UTF-8 - - diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/DfaReportingFactory.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/DfaReportingFactory.java deleted file mode 100644 index d0aac5d..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/DfaReportingFactory.java +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; -import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; -import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; -import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.util.store.DataStoreFactory; -import com.google.api.client.util.store.FileDataStoreFactory; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.DfareportingScopes; - -import java.io.IOException; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.Paths; - -/** - * Utility methods used by all DFA Reporting and Trafficking API samples. - */ -public class DfaReportingFactory { - /** Directory to store user credentials. */ - private static final java.io.File DATA_STORE_DIR = - new java.io.File(System.getProperty("user.home"), ".store/dfareporting_sample"); - - private static final HttpTransport HTTP_TRANSPORT = Utils.getDefaultTransport(); - private static final JsonFactory JSON_FACTORY = Utils.getDefaultJsonFactory(); - - /** - * Authorizes the application to access users' protected data. - * - * @return An initialized {@link Credential} object. - */ - private static Credential authorize() throws Exception { - // Load application default credentials if they're available. - Credential credential = loadApplicationDefaultCredentials(); - - // Otherwise, load credentials from the provided client secrets file. - if (credential == null) { - String clientSecretsFile = - DfaReportingFactory.class.getResource("/client_secrets.json").getFile(); - credential = loadUserCredentials(clientSecretsFile, new FileDataStoreFactory(DATA_STORE_DIR)); - } - - return credential; - } - - /** - * Attempts to load application default credentials. - * - * @return A {@link Credential} object initialized with application default credentials, or - * {@code null} if none were found. - */ - private static Credential loadApplicationDefaultCredentials() { - try { - GoogleCredential credential = GoogleCredential.getApplicationDefault(); - return credential.createScoped(DfareportingScopes.all()); - } catch (IOException ignored) { - // No application default credentials, continue to try other options. - } - - return null; - } - - /** - * Attempts to load user credentials from the provided client secrets file and persists data to - * the provided data store. - * - * @param clientSecretsFile The path to the file containing client secrets. - * @param dataStoreFactory he data store to use for caching credential information. - * @return A {@link Credential} object initialized with user account credentials. - */ - private static Credential loadUserCredentials(String clientSecretsFile, - DataStoreFactory dataStoreFactory) throws Exception { - // Load client secrets JSON file. - GoogleClientSecrets clientSecrets; - try (Reader reader = Files.newBufferedReader(Paths.get(clientSecretsFile), UTF_8)) { - clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, reader); - } - - // Set up the authorization code flow. - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, - JSON_FACTORY, clientSecrets, DfareportingScopes.all()) - .setDataStoreFactory(dataStoreFactory) - .build(); - - // Authorize and persist credential information to the data store. - return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); - } - - /** - * Performs all necessary setup steps for running requests against the API. - * - * @return An initialized {@link Dfareporting} service object. - */ - public static Dfareporting getInstance() throws Exception { - Credential credential = authorize(); - - // Create Dfareporting client. - return new Dfareporting.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName( - "dfareporting-java-samples").build(); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/ads/CreateRotationGroup.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/ads/CreateRotationGroup.java deleted file mode 100755 index 8f9d756..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/ads/CreateRotationGroup.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.ads; - -import com.google.api.client.util.DateTime; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Ad; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.ClickThroughUrl; -import com.google.api.services.dfareporting.model.CreativeAssignment; -import com.google.api.services.dfareporting.model.CreativeRotation; -import com.google.api.services.dfareporting.model.DeliverySchedule; -import com.google.api.services.dfareporting.model.PlacementAssignment; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -import java.util.Date; - -/** - * This example creates a rotation group ad in a given campaign. Start and end date for the ad must - * be within campaign start and end dates. To create creatives, run one of the Create*Creative.java - * examples. To get available placements, run GetPlacements.java. - */ -public class CreateRotationGroup { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - // Set the parameters for the new ad rotation group. - private static final String AD_NAME = "ENTER_AD_NAME_HERE"; - private static final String CAMPAIGN_ID = "ENTER_CAMPAIGN_ID_HERE"; - private static final String CREATIVE_ID = "ENTER_CREATIVE_ID_HERE"; - private static final String PLACEMENT_ID = "ENTER_PLACEMENT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String adName, - long campaignId, long creativeId, long placementId) throws Exception { - // Retrieve the campaign. - Campaign campaign = reporting.campaigns().get(profileId, campaignId).execute(); - - // Create a click-through URL. - ClickThroughUrl clickThroughUrl = new ClickThroughUrl(); - clickThroughUrl.setDefaultLandingPage(true); - - // Create a creative assignment. - CreativeAssignment creativeAssignment = new CreativeAssignment(); - creativeAssignment.setActive(true); - creativeAssignment.setCreativeId(creativeId); - creativeAssignment.setClickThroughUrl(clickThroughUrl); - - // Create a placement assignment. - PlacementAssignment placementAssignment = new PlacementAssignment(); - placementAssignment.setActive(true); - placementAssignment.setPlacementId(placementId); - - // Create a creative rotation. - CreativeRotation creativeRotation = new CreativeRotation(); - creativeRotation.setCreativeAssignments(ImmutableList.of(creativeAssignment)); - - // Create a delivery schedule. - DeliverySchedule deliverySchedule = new DeliverySchedule(); - deliverySchedule.setImpressionRatio(1L); - deliverySchedule.setPriority("AD_PRIORITY_01"); - - DateTime startDate = new DateTime(new Date()); - DateTime endDate = campaign.getEndDate(); - - // Create a rotation group. - Ad rotationGroup = new Ad(); - rotationGroup.setActive(true); - rotationGroup.setCampaignId(campaignId); - rotationGroup.setCreativeRotation(creativeRotation); - rotationGroup.setDeliverySchedule(deliverySchedule); - rotationGroup.setStartTime(startDate); - rotationGroup.setEndTime(endDate); - rotationGroup.setName(adName); - rotationGroup.setPlacementAssignments(ImmutableList.of(placementAssignment)); - rotationGroup.setType("AD_SERVING_STANDARD_AD"); - - // Insert the rotation group. - Ad result = reporting.ads().insert(profileId, rotationGroup).execute(); - - // Display the new ad ID. - System.out.printf("Ad with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long creativeId = Long.parseLong(CREATIVE_ID); - long placementId = Long.parseLong(PLACEMENT_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, AD_NAME, campaignId, creativeId, placementId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/ads/GetAds.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/ads/GetAds.java deleted file mode 100644 index bcbab04..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/ads/GetAds.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.ads; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Ad; -import com.google.api.services.dfareporting.model.AdsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays the name, ID and advertiser ID for every active ad your DFA user profile - * can see. - */ -public class GetAds { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,ads(advertiserId,id,name)"; - - AdsListResponse result; - String nextPageToken = null; - - do { - // Create and execute the ad list request. - result = reporting.ads().list(profileId).setActive(true).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Ad ad : result.getAds()) { - System.out.printf( - "Ad with ID %d and name \"%s\" is associated with advertiser ID %d.%n", ad.getId(), - ad.getName(), ad.getAdvertiserId()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getAds().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/AssignAdvertisersToAdvertiserGroup.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/AssignAdvertisersToAdvertiserGroup.java deleted file mode 100644 index c346b38..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/AssignAdvertisersToAdvertiserGroup.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Advertiser; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example assigns an advertiser to an advertiser group. - * - * CAUTION: An advertiser that has campaigns associated with it cannot be removed from an - * advertiser group once assigned. - */ -public class AssignAdvertisersToAdvertiserGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String ADVERTISER_GROUP_ID = "INSERT_ADVERTISER_GROUP_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long advertiserGroupId) throws Exception { - // Create the Advertiser and populate with the group ID to patch. - Advertiser advertiser = new Advertiser(); - advertiser.setAdvertiserGroupId(advertiserGroupId); - - // Patch the existing advertiser. - Advertiser result = - reporting.advertisers().patch(profileId, advertiserId, advertiser).execute(); - - // Print out the advertiser and advertiser group ID. - System.out.printf("Advertiser with ID %d was assigned to advertiser group \"%s\".%n", - result.getId(), result.getAdvertiserGroupId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long advertiserGroupId = Long.parseLong(ADVERTISER_GROUP_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, advertiserGroupId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiser.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiser.java deleted file mode 100644 index fb748c1..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiser.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Advertiser; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - - -/** - * This example creates an advertiser in a given DFA account. To get advertisers, see - * GetAdvertisers.java. - */ -public class CreateAdvertiser { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_NAME = "INSERT_ADVERTISER_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String advertiserName) - throws Exception { - // Create the advertiser structure. - Advertiser advertiser = new Advertiser(); - advertiser.setName(advertiserName); - advertiser.setStatus("APPROVED"); - - // Create the advertiser. - Advertiser result = reporting.advertisers().insert(profileId, advertiser).execute(); - - // Display the advertiser ID. - System.out.printf("Advertiser with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, ADVERTISER_NAME); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserGroup.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserGroup.java deleted file mode 100644 index 591212d..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserGroup.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserGroup; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates an advertiser group. To get advertiser groups, see GetAdvertiserGroups.java. - */ -public class CreateAdvertiserGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_GROUP_NAME = "INSERT_ADVERTISER_GROUP_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String advertiserGroupName) - throws Exception { - // Create advertiser group structure. - AdvertiserGroup advertiserGroup = new AdvertiserGroup(); - advertiserGroup.setName(advertiserGroupName); - - // Create advertiser group. - AdvertiserGroup result = - reporting.advertiserGroups().insert(profileId, advertiserGroup).execute(); - - // Display advertiser group ID. - System.out.printf("Advertiser Group with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, ADVERTISER_GROUP_NAME); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserLandingPage.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserLandingPage.java deleted file mode 100644 index dc35f71..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/CreateAdvertiserLandingPage.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates an advertiser landing page. - */ -public class CreateAdvertiserLandingPage { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String LANDING_PAGE_NAME = "INSERT_LANDING_PAGE_NAME_HERE"; - private static final String LANDING_PAGE_URL = "INSERT_LANDING_PAGE_URL_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - String landingPageName, String landingPageUrl) throws Exception { - // Create the landing page structure. - LandingPage landingPage = new LandingPage(); - landingPage.setAdvertiserId(advertiserId); - landingPage.setArchived(false); - landingPage.setName(landingPageName); - landingPage.setUrl(landingPageUrl); - - // Create the landing page - LandingPage result = - reporting.advertiserLandingPages().insert(profileId, landingPage).execute(); - - // Display the landing page ID. - System.out.printf("Advertiser landing page with ID %d and name \"%s\" was created.%n", - result.getId(), result.getName()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long advertiserId = Long.parseLong(ADVERTISER_ID); - - runExample(reporting, profileId, advertiserId, LANDING_PAGE_NAME, LANDING_PAGE_URL); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserGroups.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserGroups.java deleted file mode 100644 index 60d6543..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserGroups.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserGroup; -import com.google.api.services.dfareporting.model.AdvertiserGroupsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all advertiser groups for the specified user profile. - */ -public class GetAdvertiserGroups { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,advertiserGroups(id,name)"; - - // List all advertiser groups - AdvertiserGroupsListResponse result = - reporting.advertiserGroups().list(profileId).setFields(fields).execute(); - - // Display advertiser group names and IDs - if (!result.getAdvertiserGroups().isEmpty()) { - for (AdvertiserGroup group : result.getAdvertiserGroups()) { - System.out.printf("Advertiser Group with ID %d and name \"%s\" was found.%n", - group.getId(), group.getName()); - } - } else { - System.out.print("No advertiser groups found for your criteria."); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserLandingPages.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserLandingPages.java deleted file mode 100644 index 4aec5b7..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertiserLandingPages.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserLandingPagesListResponse; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all landing pages for a specified advertiser. - */ -public class GetAdvertiserLandingPages { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,landingPages(id,name,url)"; - - AdvertiserLandingPagesListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser landing pages list request. - result = reporting.advertiserLandingPages().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (LandingPage landingPage : result.getLandingPages()) { - System.out.printf( - "Advertiser landing page with ID %d, name \"%s\", and URL %s was found.%n", - landingPage.getId(), landingPage.getName(), landingPage.getUrl()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getLandingPages().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long advertiserId = Long.parseLong(ADVERTISER_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertisers.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertisers.java deleted file mode 100644 index 23b5a48..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/advertisers/GetAdvertisers.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.advertisers; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Advertiser; -import com.google.api.services.dfareporting.model.AdvertisersListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays the name, ID and spotlight configuration ID for every advertiser your DFA - * user profile can see. - */ -public class GetAdvertisers { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,advertisers(id,floodlightConfigurationId,name)"; - - AdvertisersListResponse result; - String nextPageToken = null; - - do { - // Create and execute the advertiser list request. - result = reporting.advertisers().list(profileId).setFields(fields).setPageToken(nextPageToken) - .execute(); - - for (Advertiser advertiser : result.getAdvertisers()) { - System.out.printf("Advertiser with ID %d, name \"%s\", and floodlight configuration ID %d " - + "was found.%n", advertiser.getId(), advertiser.getName(), - advertiser.getFloodlightConfigurationId()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getAdvertisers().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingServiceAccount.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingServiceAccount.java deleted file mode 100644 index 60e2023..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingServiceAccount.java +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.auth; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.DfareportingScopes; -import com.google.api.services.dfareporting.model.UserProfileList; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableSet; -import java.io.FileInputStream; - -/** - * This example demonstrates how to authenticate and make a basic request using a service account. - */ -public class AuthenticateUsingServiceAccount { - private static final String PATH_TO_JSON_FILE = "ENTER_PATH_TO_JSON_FILE_HERE"; - - /** - * An optional Google account email to impersonate. Only applicable to service accounts which have - * enabled domain-wide delegation and wish to make API requests on behalf of an account within - * their domain. Setting this field will not allow you to impersonate a user from a domain you - * don't own (e.g., gmail.com). - */ - private static final String EMAIL_TO_IMPERSONATE = ""; - - // The OAuth 2.0 scopes to request. - private static final ImmutableSet OAUTH_SCOPES = - ImmutableSet.of(DfareportingScopes.DFAREPORTING); - - private static Credential getServiceAccountCredential( - String pathToJsonFile, String emailToImpersonate) throws Exception { - // Generate a credential object from the specified JSON file. - GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(pathToJsonFile)); - - // Update the credential object with appropriate scopes and impersonation info (if applicable). - if (Strings.isNullOrEmpty(emailToImpersonate)) { - credential = credential.createScoped(OAUTH_SCOPES); - } else { - credential = - new GoogleCredential.Builder() - .setTransport(credential.getTransport()) - .setJsonFactory(credential.getJsonFactory()) - .setServiceAccountId(credential.getServiceAccountId()) - .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey()) - .setServiceAccountScopes(OAUTH_SCOPES) - // Set the email of the user you are impersonating (this can be yourself). - .setServiceAccountUser(emailToImpersonate) - .build(); - } - - return credential; - } - - public static void runExample(Dfareporting reporting) throws Exception { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = reporting.userProfiles().list().execute(); - for (int i = 0; i < profiles.getItems().size(); i++) { - System.out.printf("%d) %s%n", i + 1, profiles.getItems().get(i).getUserName()); - } - } - - public static void main(String[] args) throws Exception { - // Build service account credential. - Credential credential = getServiceAccountCredential(PATH_TO_JSON_FILE, EMAIL_TO_IMPERSONATE); - - // Create a Dfareporting client instance. - // - // Note: application name below should be replaced with a value that identifies your - // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion". - Dfareporting reporting = - new Dfareporting.Builder(credential.getTransport(), credential.getJsonFactory(), credential) - .setApplicationName("dfareporting-java-service-acct-sample") - .build(); - - runExample(reporting); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingUserAccount.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingUserAccount.java deleted file mode 100644 index 3bba0e2..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/auth/AuthenticateUsingUserAccount.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.auth; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; -import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; -import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; -import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.util.store.DataStoreFactory; -import com.google.api.client.util.store.FileDataStoreFactory; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.DfareportingScopes; -import com.google.api.services.dfareporting.model.UserProfileList; -import com.google.common.collect.ImmutableSet; -import java.nio.file.Files; -import java.nio.file.Paths; - -/** - * This example demonstrates how to authenticate and make a basic request using a user account, via - * the OAuth 2.0 - * installed application flow. - */ -public class AuthenticateUsingUserAccount { - private static final String PATH_TO_CLIENT_SECRETS = "ENTER_PATH_TO_CLIENT_SECRETS_HERE"; - - // Location where authorization credentials will be cached. - private static final java.io.File DATA_STORE_DIR = - new java.io.File(System.getProperty("user.home"), ".store/dfareporting_auth_sample"); - - // The OAuth 2.0 scopes to request. - private static final ImmutableSet OAUTH_SCOPES = - ImmutableSet.of(DfareportingScopes.DFAREPORTING); - - private static Credential getUserAccountCredential( - String pathToClientSecretsFile, DataStoreFactory dataStoreFactory) throws Exception { - HttpTransport httpTransport = Utils.getDefaultTransport(); - JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); - - // Load the client secrets JSON file. - GoogleClientSecrets clientSecrets = - GoogleClientSecrets.load( - jsonFactory, Files.newBufferedReader(Paths.get(pathToClientSecretsFile), UTF_8)); - - // Set up the authorization code flow. - // - // Note: providing a DataStoreFactory allows auth credentials to be cached, so they survive - // multiple runs of the program. This avoids prompting the user for authorization every time the - // access token expires, by remembering the refresh token. - GoogleAuthorizationCodeFlow flow = - new GoogleAuthorizationCodeFlow.Builder( - httpTransport, jsonFactory, clientSecrets, OAUTH_SCOPES) - .setDataStoreFactory(dataStoreFactory) - .build(); - - // Authorize and persist credentials to the data store. - // - // Note: the "user" value below is used to identify a specific set of credentials in the data - // store. You may provide different values here to persist credentials for multiple users to - // the same data store. - Credential credential = - new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); - - return credential; - } - - public static void runExample(Dfareporting reporting) throws Exception { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = reporting.userProfiles().list().execute(); - for (int i = 0; i < profiles.getItems().size(); i++) { - System.out.printf("%d) %s%n", i + 1, profiles.getItems().get(i).getUserName()); - } - } - - public static void main(String[] args) throws Exception { - // Build installed application credential. - Credential credential = - getUserAccountCredential(PATH_TO_CLIENT_SECRETS, new FileDataStoreFactory(DATA_STORE_DIR)); - - // Create a Dfareporting client instance. - // - // Note: application name below should be replaced with a value that identifies your - // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion". - Dfareporting reporting = - new Dfareporting.Builder(credential.getTransport(), credential.getJsonFactory(), credential) - .setApplicationName("dfareporting-java-installed-app-sample") - .build(); - - runExample(reporting); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaign.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaign.java deleted file mode 100644 index 6e4fdbd..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaign.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.campaigns; - -import com.google.api.client.util.DateTime; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserLandingPagesListResponse; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import com.google.common.collect.ImmutableList; -import java.util.Calendar; - -/** - * This example creates a campaign associated with a given advertiser. To create an advertiser, run - * CreateAdvertiser.java. - */ -public class CreateCampaign { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String campaignName, - long advertiserId) throws Exception { - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(reporting, profileId, advertiserId); - - // Create the campaign structure. - Campaign campaign = new Campaign(); - campaign.setName(campaignName); - campaign.setAdvertiserId(advertiserId); - campaign.setArchived(false); - campaign.setDefaultLandingPageId(defaultLandingPage.getId()); - - // Set the campaign start date. This example uses today's date. - Calendar today = Calendar.getInstance(); - DateTime startDate = new DateTime(true, today.getTimeInMillis(), null); - campaign.setStartDate(startDate); - - // Set the campaign end date. This example uses one month from today's date. - Calendar nextMonth = Calendar.getInstance(); - nextMonth.add(Calendar.MONTH, 1); - DateTime endDate = new DateTime(true, nextMonth.getTimeInMillis(), null); - campaign.setEndDate(endDate); - - // Insert the campaign. - Campaign result = reporting.campaigns().insert(profileId, campaign).execute(); - - // Display the new campaign ID. - System.out.printf("Campaign with ID %d was created.%n", result.getId()); - } - - private static LandingPage getAdvertiserLandingPage(Dfareporting reporting, long profileId, - long advertiserId) throws Exception { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesListResponse landingPages = reporting.advertiserLandingPages() - .list(profileId).setAdvertiserIds(ImmutableList.of(advertiserId)).setMaxResults(1) - .execute(); - - if (landingPages.getLandingPages() == null || landingPages.getLandingPages().isEmpty()) { - throw new IllegalStateException( - "No landing pages found for advertiser with ID " + advertiserId); - } - - return landingPages.getLandingPages().get(0); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CAMPAIGN_NAME, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaignEventTag.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaignEventTag.java deleted file mode 100644 index 1b6d14c..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/CreateCampaignEventTag.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.campaigns; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.EventTag; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates an event tag for the specified campaign. - */ -public class CreateCampaignEventTag { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String EVENT_TAG_NAME = "INSERT_EVENT_TAG_NAME_HERE"; - private static final String EVENT_TAG_URL = "INSERT_EVENT_TAG_URL_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long campaignId, - String eventTagName, String eventTagUrl) throws Exception { - // Create the event tag structure. - EventTag eventTag = new EventTag(); - eventTag.setCampaignId(campaignId); - eventTag.setName(eventTagName); - eventTag.setStatus("ENABLED"); - eventTag.setType("CLICK_THROUGH_EVENT_TAG"); - eventTag.setUrl(eventTagUrl); - - // Insert the campaign. - EventTag result = reporting.eventTags().insert(profileId, eventTag).execute(); - - // Display the new campaign ID. - System.out.printf("Event Tag with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, campaignId, EVENT_TAG_NAME, EVENT_TAG_URL); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/GetCampaigns.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/GetCampaigns.java deleted file mode 100644 index 73f9333..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/campaigns/GetCampaigns.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.campaigns; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.CampaignsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all existing campaigns for the specified user profile. - */ -public class GetCampaigns { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,campaigns(id,name)"; - - CampaignsListResponse campaigns; - String nextPageToken = null; - - do { - // Create and execute the campaigns list request. - campaigns = reporting.campaigns().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Campaign campaign : campaigns.getCampaigns()) { - System.out.printf("Campaign with ID %d and name \"%s\" was found.%n", campaign.getId(), - campaign.getName()); - } - - // Update the next page token. - nextPageToken = campaigns.getNextPageToken(); - } while (!campaigns.getCampaigns().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineMobileConversion.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineMobileConversion.java deleted file mode 100644 index fd900c4..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineMobileConversion.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2016 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertResponse; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example inserts an offline conversion attributed to a mobile device ID, and associated - * with the specified Floodlight activity. To create an activity, run CreateFloodlightActivity.java. - */ -public class InsertOfflineMobileConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CONVERSION_MOBILE_ID = "INSERT_CONVERSION_MOBILE_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long floodlightActivityId, - String mobileDeviceId) throws Exception { - long currentTimeInMilliseconds = System.currentTimeMillis(); - - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - Conversion conversion = new Conversion(); - conversion.setMobileDeviceId(mobileDeviceId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(String.valueOf(currentTimeInMilliseconds)); - conversion.setTimestampMicros(currentTimeInMilliseconds * 1000); - - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.setConversions(ImmutableList.of(conversion)); - - ConversionsBatchInsertResponse response = reporting.conversions() - .batchinsert(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully inserted conversion for mobile device ID %s.%n", - mobileDeviceId); - } else { - System.out.printf("Error(s) inserting conversion for mobile device ID %s:%n", - mobileDeviceId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_MOBILE_ID); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineUserConversion.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineUserConversion.java deleted file mode 100644 index c066e12..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/InsertOfflineUserConversion.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2016 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchInsertResponse; -import com.google.api.services.dfareporting.model.EncryptionInfo; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example inserts an offline conversion attributed to an encrypted user ID, and associated - * with the specified Floodlight activity. To create an activity, run CreateFloodlightActivity.java. - */ -public class InsertOfflineUserConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CONVERSION_USER_ID = "INSERT_CONVERSION_USER_ID_HERE"; - private static final String ENCRYPTION_ENTITY_ID = "INSERT_ENCRYPTION_ENTITY_ID_HERE"; - private static final String ENCRYPTION_ENTITY_TYPE = "INSERT_ENCRYPTION_ENTITY_TYPE_HERE"; - private static final String ENCRYPTION_SOURCE = "INSERT_ENCRYPTION_SOURCE_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long floodlightActivityId, - String encryptedUserId, long encryptionEntityId, String encryptionEntityType, - String encryptionSource) throws Exception { - long currentTimeInMilliseconds = System.currentTimeMillis(); - - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - Conversion conversion = new Conversion(); - conversion.setEncryptedUserId(encryptedUserId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(String.valueOf(currentTimeInMilliseconds)); - conversion.setTimestampMicros(currentTimeInMilliseconds * 1000); - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.setEncryptionEntityId(encryptionEntityId); - encryptionInfo.setEncryptionEntityType(encryptionEntityType); - encryptionInfo.setEncryptionSource(encryptionSource); - - ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); - request.setConversions(ImmutableList.of(conversion)); - request.setEncryptionInfo(encryptionInfo); - - ConversionsBatchInsertResponse response = reporting.conversions() - .batchinsert(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully inserted conversion for encrypted user ID %s.%n", - encryptedUserId); - } else { - System.out.printf("Error(s) inserting conversion for encrypted user ID %s:%n", - encryptedUserId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long encryptionEntityId = Long.parseLong(ENCRYPTION_ENTITY_ID); - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_USER_ID, encryptionEntityId, - ENCRYPTION_ENTITY_TYPE, ENCRYPTION_SOURCE); - } -} - diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineMobileConversion.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineMobileConversion.java deleted file mode 100644 index 5e799f6..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineMobileConversion.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateResponse; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example updates the quantity and value of a conversion attributed to a mobile device ID. To - * create a conversion attributed to a mobile device ID, run InsertOfflineMobileConversion.java. - */ -public class UpdateOfflineMobileConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Values that identify an existing conversion. - private static final String CONVERSION_MOBILE_ID = "INSERT_CONVERSION_MOBILE_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - private static final String ORDINAL = "INSERT_ORDINAL_VALUE_HERE"; - private static final String TIMESTAMP = "INSERT_TIMESTAMP_IN_MICROSECONDS_HERE"; - - // Values to update for the specified conversion. - private static final String NEW_QUANTITY = "INSERT_NEW_CONVERSION_QUANTITY_HERE"; - private static final String NEW_VALUE = "INSERT_NEW_CONVERSION_VALUE_HERE"; - - public static void runExample( - Dfareporting reporting, long profileId, long floodlightActivityId, String mobileDeviceId, - String ordinal, long timestampMicros, long newQuantity, double newValue) throws Exception { - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - // Create a conversion object populated with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.setMobileDeviceId(mobileDeviceId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(ordinal); - conversion.setTimestampMicros(timestampMicros); - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.setQuantity(newQuantity); - conversion.setValue(newValue); - - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.setConversions(ImmutableList.of(conversion)); - - ConversionsBatchUpdateResponse response = reporting.conversions() - .batchupdate(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully updated conversion for mobile device ID %s.%n", - mobileDeviceId); - } else { - System.out.printf("Error(s) updating conversion for mobile device ID %s:%n", - mobileDeviceId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long newQuantity = Long.parseLong(NEW_QUANTITY); - long profileId = Long.parseLong(USER_PROFILE_ID); - long timestampMicros = Long.parseLong(TIMESTAMP); - - double newValue = Double.parseDouble(NEW_VALUE); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_MOBILE_ID, - ORDINAL, timestampMicros, newQuantity, newValue); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineUserConversion.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineUserConversion.java deleted file mode 100644 index a2a3baf..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/conversions/UpdateOfflineUserConversion.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.conversions; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Conversion; -import com.google.api.services.dfareporting.model.ConversionError; -import com.google.api.services.dfareporting.model.ConversionStatus; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateRequest; -import com.google.api.services.dfareporting.model.ConversionsBatchUpdateResponse; -import com.google.api.services.dfareporting.model.EncryptionInfo; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example updates the quantity and value of a conversion attributed to an encrypted user ID. - * To create a conversion attributed to an encrypted user ID, run InsertOfflineUserConversion.java. - */ -public class UpdateOfflineUserConversion { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Values that identify an existing conversion. - private static final String CONVERSION_USER_ID = "INSERT_CONVERSION_USER_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "INSERT_FLOODLIGHT_ACTIVITY_ID_HERE"; - private static final String ORDINAL = "INSERT_ORDINAL_VALUE_HERE"; - private static final String TIMESTAMP = "INSERT_TIMESTAMP_IN_MICROSECONDS_HERE"; - - // Values that specify how the existing conversion is encrypted. - private static final String ENCRYPTION_ENTITY_ID = "INSERT_ENCRYPTION_ENTITY_ID_HERE"; - private static final String ENCRYPTION_ENTITY_TYPE = "INSERT_ENCRYPTION_ENTITY_TYPE_HERE"; - private static final String ENCRYPTION_SOURCE = "INSERT_ENCRYPTION_SOURCE_HERE"; - - // Values to update for the specified conversion. - private static final String NEW_QUANTITY = "INSERT_NEW_CONVERSION_QUANTITY_HERE"; - private static final String NEW_VALUE = "INSERT_NEW_CONVERSION_VALUE_HERE"; - - public static void runExample( - Dfareporting reporting, long profileId, long floodlightActivityId, String encryptedUserId, - long encryptionEntityId, String encryptionEntityType, String encryptionSource, String ordinal, - long timestampMicros, long newQuantity, double newValue) throws Exception { - // Find Floodlight configuration ID based on the provided activity ID. - FloodlightActivity floodlightActivity = reporting.floodlightActivities() - .get(profileId, floodlightActivityId).execute(); - long floodlightConfigurationId = floodlightActivity.getFloodlightConfigurationId(); - - // Create a conversion object populated with values that identify the conversion to update. - Conversion conversion = new Conversion(); - conversion.setEncryptedUserId(encryptedUserId); - conversion.setFloodlightActivityId(floodlightActivityId); - conversion.setFloodlightConfigurationId(floodlightConfigurationId); - conversion.setOrdinal(ordinal); - conversion.setTimestampMicros(timestampMicros); - - // Set the fields to be updated. These fields are required; to preserve a value from the - // existing conversion, it must be copied over manually. - conversion.setQuantity(newQuantity); - conversion.setValue(newValue); - - // Create the encryption info. - EncryptionInfo encryptionInfo = new EncryptionInfo(); - encryptionInfo.setEncryptionEntityId(encryptionEntityId); - encryptionInfo.setEncryptionEntityType(encryptionEntityType); - encryptionInfo.setEncryptionSource(encryptionSource); - - ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); - request.setConversions(ImmutableList.of(conversion)); - request.setEncryptionInfo(encryptionInfo); - - ConversionsBatchUpdateResponse response = reporting.conversions() - .batchupdate(profileId, request).execute(); - - if (!response.getHasFailures()) { - System.out.printf("Successfully updated conversion for encrypted user ID %s.%n", - encryptedUserId); - } else { - System.out.printf("Error(s) updating conversion for encrypted user ID %s:%n", - encryptedUserId); - - // Retrieve the conversion status and report any errors found. If multiple conversions - // were included in the original request, the response would contain a status for each. - ConversionStatus status = response.getStatus().get(0); - for (ConversionError error : status.getErrors()) { - System.out.printf("\t[%s]: %s.%n", error.getCode(), error.getMessage()); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long encryptionEntityId = Long.parseLong(ENCRYPTION_ENTITY_ID); - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long newQuantity = Long.parseLong(NEW_QUANTITY); - long profileId = Long.parseLong(USER_PROFILE_ID); - long timestampMicros = Long.parseLong(TIMESTAMP); - - double newValue = Double.parseDouble(NEW_VALUE); - - runExample(reporting, profileId, floodlightActivityId, CONVERSION_USER_ID, encryptionEntityId, - ENCRYPTION_ENTITY_TYPE, ENCRYPTION_SOURCE, ORDINAL, timestampMicros, newQuantity, newValue); - } -} - diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/AssignCreativeToCampaign.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/AssignCreativeToCampaign.java deleted file mode 100644 index 5b7d3a9..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/AssignCreativeToCampaign.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CampaignCreativeAssociation; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example assigns a given creative to a given campaign. Note that both the creative and - * campaign must be associated with the same advertiser. - */ -public class AssignCreativeToCampaign { - private static final String USER_PROFILE_ID = "INSERT_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String CREATIVE_ID = "INSERT_CREATIVE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long campaignId, - long creativeId) throws Exception { - // Create the campaign creative association structure. - CampaignCreativeAssociation association = new CampaignCreativeAssociation(); - association.setCreativeId(creativeId); - - // Insert the association. - CampaignCreativeAssociation result = reporting - .campaignCreativeAssociations().insert(profileId, campaignId, association) - .execute(); - - // Display a success message. - System.out.printf("Creative with ID %d is now associated with campaign %d.%n", - result.getCreativeId(), campaignId); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long creativeId = Long.parseLong(CREATIVE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, campaignId, creativeId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeField.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeField.java deleted file mode 100644 index 20df281..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeField.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeField; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a creative field associated with a given advertiser. To get an advertiser - * ID, run GetAdvertisers.java. - */ -public class CreateCreativeField { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String CREATIVE_FIELD_NAME = "INSERT_CREATIVE_FIELD_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String creativeFieldName, - long advertiserId) throws Exception { - // Create the creative field. - CreativeField creativeField = new CreativeField(); - creativeField.setName(creativeFieldName); - creativeField.setAdvertiserId(advertiserId); - - // Insert the creative field. - CreativeField result = reporting.creativeFields().insert(profileId, creativeField).execute(); - - // Display the new creative field ID. - System.out.printf("Creative field with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CREATIVE_FIELD_NAME, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeFieldValue.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeFieldValue.java deleted file mode 100644 index d234cd3..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeFieldValue.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeFieldValue; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a creative field value associated with a given creative field. To get the - * creative field ID, run GetCreativeFields.java. - */ -public class CreateCreativeFieldValue { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CREATIVE_FIELD_ID = "INSERT_CREATIVE_FIELD_ID_HERE"; - private static final String CREATIVE_FIELD_VALUE_NAME = "INSERT_CREATIVE_FIELD_VALUE_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, - String creativeFieldValueName, long creativeFieldId) throws Exception { - // Create the creative field value. - CreativeFieldValue creativeFieldValue = new CreativeFieldValue(); - creativeFieldValue.setValue(creativeFieldValueName); - - // Insert the creative field value. - CreativeFieldValue result = reporting.creativeFieldValues() - .insert(profileId, creativeFieldId, creativeFieldValue).execute(); - - // Display the new creative field value ID. - System.out.printf("Creative field value with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long creativeFieldId = Long.parseLong(CREATIVE_FIELD_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CREATIVE_FIELD_VALUE_NAME, creativeFieldId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeGroup.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeGroup.java deleted file mode 100644 index b900b41..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateCreativeGroup.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeGroup; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a creative group associated with a given advertiser. To get an advertiser - * ID, run getAdvertisers.java. Valid group numbers are limited to 1 or 2. - */ -public class CreateCreativeGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String CREATIVE_GROUP_NAME = "INSERT_CREATIVE_GROUP_NAME_HERE"; - private static final String GROUP_NUMBER = "INSERT_GROUP_NUMBER_HERE"; - - - public static void runExample(Dfareporting reporting, long profileId, String creativeGroupName, - int groupNumber, long advertiserId) throws Exception { - // Create the creative group. - CreativeGroup creativeGroup = new CreativeGroup(); - creativeGroup.setName(creativeGroupName); - creativeGroup.setGroupNumber(groupNumber); - creativeGroup.setAdvertiserId(advertiserId); - - // Insert the creative group. - CreativeGroup result = reporting.creativeGroups().insert(profileId, creativeGroup).execute(); - - // Display the new creative group ID. - System.out.printf("Creative group with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - int groupNumber = Integer.parseInt(GROUP_NUMBER); - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CREATIVE_GROUP_NAME, groupNumber, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayImageGalleryCreative.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayImageGalleryCreative.java deleted file mode 100644 index dc666a6..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayImageGalleryCreative.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ClickTag; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates a display image gallery creative associated - * with a given advertiser. To get a size ID, run GetSize.java. - */ -public class CreateDisplayImageGalleryCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - // First image asset values. - private static final String IMAGE_ASSET1_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET1_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - // Second image asset values. - private static final String IMAGE_ASSET2_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET2_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long sizeId) throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setAutoAdvanceImages(true); - creative.setName("Test display image gallery creative"); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY_IMAGE_GALLERY"); - - // Upload the first image asset. - CreativeAssetId imageAsset1Id = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET1_NAME, PATH_TO_IMAGE_ASSET1_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset imageAsset1 = - new CreativeAsset().setAssetIdentifier(imageAsset1Id).setRole("PRIMARY"); - - // Upload the second image asset. - CreativeAssetId imageAsset2Id = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET2_NAME, PATH_TO_IMAGE_ASSET2_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset imageAsset2 = - new CreativeAsset().setAssetIdentifier(imageAsset2Id).setRole("PRIMARY"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(imageAsset1, imageAsset2)); - - // Create a click tag for the first image asset. - ClickTag clickTag1 = - new ClickTag().setName(imageAsset1Id.getName()).setEventName(imageAsset1Id.getName()); - - // Create a click tag for the second image asset. - ClickTag clickTag2 = - new ClickTag().setName(imageAsset2Id.getName()).setEventName(imageAsset2Id.getName()); - - // Add the click tags. - creative.setClickTags(ImmutableList.of(clickTag1, clickTag2)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Display image gallery creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, sizeId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayRedirectCreative.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayRedirectCreative.java deleted file mode 100644 index dd9d3bf..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateDisplayRedirectCreative.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a display redirect creative associated with a given advertiser. To get a - * size ID, run GetSize.java. - */ -public class CreateDisplayRedirectCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String IMAGE_URL = "INSERT_IMAGE_URL_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - String imageUrl, long sizeId) throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test display redirect creative"); - creative.setRedirectUrl(imageUrl); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY_REDIRECT"); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Display redirect creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, IMAGE_URL, sizeId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateHTML5DisplayCreative.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateHTML5DisplayCreative.java deleted file mode 100644 index 69cd51c..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateHTML5DisplayCreative.java +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.AdvertiserLandingPagesListResponse; -import com.google.api.services.dfareporting.model.ClickTag; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.CreativeClickThroughUrl; -import com.google.api.services.dfareporting.model.LandingPage; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.dfareporting.model.TargetWindow; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an HTML5 display creative associated with a - * given advertiser. To get a size ID, run GetSize.java. - */ -public class CreateHTML5DisplayCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - // HTML5 asset values. - private static final String HTML5_ASSET_NAME = "INSERT_HTML5_ASSET_NAME_HERE"; - private static final String PATH_TO_HTML5_ASSET_FILE = "INSERT_PATH_TO_HTML5_ASSET_FILE_HERE"; - - // Backup image asset values. - private static final String IMAGE_ASSET_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long sizeId) throws Exception { - // Locate an advertiser landing page to use as a default. - LandingPage defaultLandingPage = getAdvertiserLandingPage(reporting, profileId, advertiserId); - - // Create the creative structure. - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test HTML5 display creative"); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY"); - - // Upload the HTML5 asset. - CreativeAssetId html5AssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, HTML5_ASSET_NAME, PATH_TO_HTML5_ASSET_FILE, "HTML").getAssetIdentifier(); - - CreativeAsset html5Asset = - new CreativeAsset().setAssetIdentifier(html5AssetId).setRole("PRIMARY"); - - // Upload the backup image asset (note: asset type must be set to HTML_IMAGE). - CreativeAssetId imageAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET_NAME, PATH_TO_IMAGE_ASSET_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset backupImageAsset = - new CreativeAsset().setAssetIdentifier(imageAssetId).setRole("BACKUP_IMAGE"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(html5Asset, backupImageAsset)); - - // Configure the backup image. - creative.setBackupImageClickThroughUrl( - new CreativeClickThroughUrl().setLandingPageId(defaultLandingPage.getId())); - creative.setBackupImageReportingLabel("backup"); - creative.setBackupImageTargetWindow(new TargetWindow().setTargetWindowOption("NEW_WINDOW")); - - // Add a click tag. - ClickTag clickTag = - new ClickTag().setName("clickTag").setEventName("exit").setClickThroughUrl( - new CreativeClickThroughUrl().setLandingPageId(defaultLandingPage.getId())); - creative.setClickTags(ImmutableList.of(clickTag)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("HTML5 display creative with ID %d was created.%n", result.getId()); - } - - private static LandingPage getAdvertiserLandingPage(Dfareporting reporting, long profileId, - long advertiserId) throws Exception { - // Retrieve a single landing page from the specified advertiser. - AdvertiserLandingPagesListResponse landingPages = reporting.advertiserLandingPages() - .list(profileId).setAdvertiserIds(ImmutableList.of(advertiserId)).setMaxResults(1) - .execute(); - - if (landingPages.getLandingPages() == null || landingPages.getLandingPages().isEmpty()) { - throw new IllegalStateException( - "No landing pages found for advertiser with ID " + advertiserId); - } - - return landingPages.getLandingPages().get(0); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, sizeId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateImageDisplayCreative.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateImageDisplayCreative.java deleted file mode 100644 index db77a52..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateImageDisplayCreative.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an image display creative associated with a - * given advertiser. To get a size ID, run GetSize.java. - */ -public class CreateImageDisplayCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - // Image asset values. - private static final String IMAGE_ASSET_NAME = "INSERT_IMAGE_ASSET_NAME_HERE"; - private static final String PATH_TO_IMAGE_ASSET_FILE = "INSERT_PATH_TO_IMAGE_ASSET_FILE_HERE"; - - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long sizeId) throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test image display creative"); - creative.setSize(new Size().setId(sizeId)); - creative.setType("DISPLAY"); - - // Upload the image asset. - CreativeAssetId imageAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, IMAGE_ASSET_NAME, PATH_TO_IMAGE_ASSET_FILE, "HTML_IMAGE") - .getAssetIdentifier(); - - CreativeAsset asset = new CreativeAsset().setAssetIdentifier(imageAssetId).setRole("PRIMARY"); - - // Add the creative asset. - creative.setCreativeAssets(ImmutableList.of(asset)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Image display creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId, sizeId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamAudioCreative.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamAudioCreative.java deleted file mode 100644 index c3152b9..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamAudioCreative.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an in-stream audio creative associated with a - * given advertiser. - */ -public class CreateInstreamAudioCreative { - private static final String USER_PROFILE_ID = "INSERT_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - // Image asset values. - private static final String AUDIO_ASSET_NAME = "INSERT_AUDIO_ASSET_NAME_HERE"; - private static final String PATH_TO_AUDIO_ASSET_FILE = "INSERT_PATH_TO_AUDIO_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test in-stream audio creative"); - creative.setType("INSTREAM_AUDIO"); - - // Upload the audio asset - CreativeAssetId audioAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, AUDIO_ASSET_NAME, PATH_TO_AUDIO_ASSET_FILE, "AUDIO").getAssetIdentifier(); - - CreativeAsset audioAsset = - new CreativeAsset().setAssetIdentifier(audioAssetId).setRole("PARENT_AUDIO"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(audioAsset)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("In-stream audio creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamVideoCreative.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamVideoCreative.java deleted file mode 100644 index 89a2de5..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateInstreamVideoCreative.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; -import com.google.common.collect.ImmutableList; - -/** - * This example uploads creative assets and creates an in-stream video creative associated with a - * given advertiser. - */ -public class CreateInstreamVideoCreative { - private static final String USER_PROFILE_ID = "INSERT_PROFILE_ID_HERE"; - - // Creative values. - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - // Image asset values. - private static final String VIDEO_ASSET_NAME = "INSERT_VIDEO_ASSET_NAME_HERE"; - private static final String PATH_TO_VIDEO_ASSET_FILE = "INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test in-stream video creative"); - creative.setType("INSTREAM_VIDEO"); - - // Upload the video asset - CreativeAssetId videoAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId, - advertiserId, VIDEO_ASSET_NAME, PATH_TO_VIDEO_ASSET_FILE, "VIDEO").getAssetIdentifier(); - - CreativeAsset videoAsset = - new CreativeAsset().setAssetIdentifier(videoAssetId).setRole("PARENT_VIDEO"); - - // Add the creative assets. - creative.setCreativeAssets(ImmutableList.of(videoAsset)); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("In-stream video creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateTrackingCreative.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateTrackingCreative.java deleted file mode 100644 index b088939..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/CreateTrackingCreative.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a tracking creative associated with a given advertiser. - */ -public class CreateTrackingCreative { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - Creative creative = new Creative(); - creative.setAdvertiserId(advertiserId); - creative.setName("Test tracking creative"); - creative.setType("TRACKING_TEXT"); - - Creative result = reporting.creatives().insert(profileId, creative).execute(); - - // Display the new creative ID. - System.out.printf("Tracking creative with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFieldValues.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFieldValues.java deleted file mode 100644 index 75650fc..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFieldValues.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeFieldValue; -import com.google.api.services.dfareporting.model.CreativeFieldValuesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example retrieves available creative field values for a given string and displays the names - * and IDs. - */ -public class GetCreativeFieldValues { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String CREATIVE_FIELD_ID = "ENTER_CREATIVE_FIELD_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long creativeFieldId) - throws Exception { - CreativeFieldValuesListResponse values; - String nextPageToken = null; - - do { - // Create and execute the creative field values list request. - values = reporting.creativeFieldValues().list(profileId, creativeFieldId) - .setPageToken(nextPageToken).execute(); - - for (CreativeFieldValue value : values.getCreativeFieldValues()) { - System.out.printf("Found creative field value with ID %d and value \"%s\".%n", - value.getId(), value.getValue()); - } - - // Update the next page token. - nextPageToken = values.getNextPageToken(); - } while (!values.getCreativeFieldValues().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long creativeFieldId = Long.parseLong(CREATIVE_FIELD_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, creativeFieldId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFields.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFields.java deleted file mode 100644 index 471e95e..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeFields.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeField; -import com.google.api.services.dfareporting.model.CreativeFieldsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all creative fields. - */ -public class GetCreativeFields { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - CreativeFieldsListResponse fields; - String nextPageToken = null; - - do { - // Create and execute the creative fields list request. - fields = reporting.creativeFields().list(profileId).setPageToken(nextPageToken).execute(); - - for (CreativeField field : fields.getCreativeFields()) { - System.out.printf("Found creative field with ID %d and name \"%s\".%n", field.getId(), - field.getName()); - } - - // Update the next page token. - nextPageToken = fields.getNextPageToken(); - } while (!fields.getCreativeFields().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeGroups.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeGroups.java deleted file mode 100644 index f37bcd4..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreativeGroups.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeGroup; -import com.google.api.services.dfareporting.model.CreativeGroupsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all creative groups. - */ -public class GetCreativeGroups { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - CreativeGroupsListResponse groups; - String nextPageToken = null; - - do { - // Create and execute the creative groups list request. - groups = reporting.creativeGroups().list(profileId).setPageToken(nextPageToken).execute(); - - for (CreativeGroup group : groups.getCreativeGroups()) { - System.out.printf("Found creative group with ID %d and name \"%s\".%n", group.getId(), - group.getName()); - } - - // Update the next page token. - nextPageToken = groups.getNextPageToken(); - } while (!groups.getCreativeGroups().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreatives.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreatives.java deleted file mode 100644 index 3dd4aef..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/GetCreatives.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all existing active creatives for a given advertiser. To get an advertiser ID, - * run GetAdvertisers.java. - */ -public class GetCreatives { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,creatives(id,name,type)"; - - CreativesListResponse groups; - String nextPageToken = null; - - do { - // Create and execute the creatives list request. - groups = reporting.creatives().list(profileId).setActive(true).setAdvertiserId(advertiserId) - .setFields(fields).setPageToken(nextPageToken).execute(); - - for (Creative group : groups.getCreatives()) { - System.out.printf("Found %s creative with ID %d and name \"%s\".%n", group.getType(), - group.getId(), group.getName()); - } - - // Update the next page token. - nextPageToken = groups.getNextPageToken(); - } while (!groups.getCreatives().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/assets/CreativeAssetUtils.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/assets/CreativeAssetUtils.java deleted file mode 100644 index d2feab7..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/creatives/assets/CreativeAssetUtils.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.creatives.assets; - -import com.google.api.client.http.InputStreamContent; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CreativeAssetId; -import com.google.api.services.dfareporting.model.CreativeAssetMetadata; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.net.FileNameMap; -import java.net.URLConnection; - -/** - * Creative asset utilities used by DFA Reporting and Trafficking API creative examples. - */ -public class CreativeAssetUtils { - - /** - * Uploads a creative asset and associates it with the specified advertiser. - * - * @param reporting An initialized {@link Dfareporting} service object - * @param profileId The current user's profile ID - * @param advertiserId The advertiser to associate this creative asset with - * @param assetName A suggested name for the asset - * @param assetFile The path to the asset file to be uploaded - * @param assetType The CreativeAssetId type of the asset - * @return A {@link CreativeAssetMetadata} populated with the name of the asset after insert. - */ - public static CreativeAssetMetadata uploadAsset(Dfareporting reporting, long profileId, - long advertiserId, String assetName, String assetFile, String assetType) throws Exception { - // Open the asset file. - File file = new File(assetFile); - - // Prepare an input stream. - String contentType = getMimeType(assetFile); - InputStreamContent assetContent = - new InputStreamContent(contentType, new BufferedInputStream(new FileInputStream(file))); - assetContent.setLength(file.length()); - - // Create the creative asset ID and Metadata. - CreativeAssetId assetId = new CreativeAssetId(); - assetId.setName(assetName); - assetId.setType(assetType); - - CreativeAssetMetadata metaData = new CreativeAssetMetadata(); - metaData.setAssetIdentifier(assetId); - - // Insert the creative. - CreativeAssetMetadata result = reporting.creativeAssets() - .insert(profileId, advertiserId, metaData, assetContent).execute(); - - // Display the new asset name. - System.out.printf("Creative asset was saved with name \"%s\".%n", - result.getAssetIdentifier().getName()); - - return result; - } - - /** - * Attempts to determine the MIME type of the specified file. If no type is detected, falls back - * to application/octet-stream. - * - * @param fileName The name of the file to find a MIME type for. - * @return The MIME type to use for uploading this file. - * @see FileNameMap#getContentTypeFor(String) - */ - private static String getMimeType(String fileName) { - FileNameMap fileNameMap = URLConnection.getFileNameMap(); - String mimeType = fileNameMap.getContentTypeFor(fileName); - - if (mimeType != null) { - return mimeType; - } - - return "application/octet-stream"; - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivity.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivity.java deleted file mode 100755 index 7a6dc37..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivity.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a floodlight activity in a given activity group. To create an activity - * group, run CreateFloodlightActivityGroup.java. - */ -public class CreateFloodlightActivity { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ACTIVITY_GROUP_ID = "INSERT_ACTIVITY_GROUP_ID_HERE"; - private static final String ACTIVITY_NAME = "INSERT_ACTIVITY_NAME_HERE"; - private static final String URL = "INSERT_EXPECTED_URL_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String activityName, - String url, long activityGroupId) throws Exception { - // Set floodlight activity structure. - FloodlightActivity activity = new FloodlightActivity(); - activity.setName(activityName); - activity.setCountingMethod("STANDARD_COUNTING"); - activity.setExpectedUrl(url); - activity.setFloodlightActivityGroupId(activityGroupId); - activity.setFloodlightTagType("GLOBAL_SITE_TAG"); - - // Create the floodlight tag activity. - FloodlightActivity result = - reporting.floodlightActivities().insert(profileId, activity).execute(); - - // Display new floodlight activity ID. - if (result != null) { - System.out.printf("Floodlight activity with ID %d was created.%n", result.getId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long activityGroupId = Long.parseLong(ACTIVITY_GROUP_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, ACTIVITY_NAME, URL, activityGroupId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivityGroup.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivityGroup.java deleted file mode 100755 index 9d69dd0..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivityGroup.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivityGroup; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a new activity group for a given floodlight configuration. To get a - * floodlight tag configuration ID, run GetAdvertisers.java. - */ -public class CreateFloodlightActivityGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String GROUP_NAME = "INSERT_GROUP_NAME_HERE"; - private static final String FLOODLIGHT_CONFIGURATION_ID = - "INSERT_FLOODLIGHT_CONFIGURATION_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String groupName, - long floodlightConfigurationId) throws Exception { - // Create the floodlight activity group. - FloodlightActivityGroup floodlightActivityGroup = new FloodlightActivityGroup(); - floodlightActivityGroup.setName(groupName); - floodlightActivityGroup.setFloodlightConfigurationId(floodlightConfigurationId); - floodlightActivityGroup.setType("COUNTER"); - - // Insert the activity group. - FloodlightActivityGroup result = - reporting.floodlightActivityGroups().insert(profileId, floodlightActivityGroup).execute(); - - // Display the new activity group ID. - if (result != null) { - System.out.printf("Activity group with ID %d was created.%n", result.getId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long floodlightConfigurationId = Long.parseLong(FLOODLIGHT_CONFIGURATION_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, GROUP_NAME, floodlightConfigurationId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/DownloadFloodlightTags.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/DownloadFloodlightTags.java deleted file mode 100755 index 0db3f1f..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/DownloadFloodlightTags.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.FloodlightActivities.Generatetag; -import com.google.api.services.dfareporting.model.FloodlightActivitiesGenerateTagResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example downloads activity tags for a given floodlight activity. - */ -public class DownloadFloodlightTags { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ACTIVITY_ID = "ENTER_ACTIVITY_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long activityId) - throws Exception { - // Generate the floodlight activity tag. - Generatetag request = reporting.floodlightActivities().generatetag(profileId); - request.setFloodlightActivityId(activityId); - - FloodlightActivitiesGenerateTagResponse response = request.execute(); - - if (response.getGlobalSiteTagGlobalSnippet() != null) { - // This is a global site tag, display both the global snippet and event snippet. - System.out.printf("Global site tag global snippet:%n%n%s", - response.getGlobalSiteTagGlobalSnippet()); - System.out.printf("%n%nGlobal site tag event snippet:%n%n%s", - response.getFloodlightActivityTag()); - } else { - // This is an image or iframe tag. - System.out.printf("Floodlight activity tag:%n%n%s", response.getFloodlightActivityTag()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long activityId = Long.parseLong(ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, activityId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivities.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivities.java deleted file mode 100644 index a1bdd33..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivities.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivitiesListResponse; -import com.google.api.services.dfareporting.model.FloodlightActivity; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays floodlight activities for a given advertiser. - * - * To create an advertiser, run create_advertiser.py. - */ -public class GetFloodlightActivities { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,floodlightActivities(id,name)"; - - FloodlightActivitiesListResponse activities; - String nextPageToken = null; - - do { - // Create and execute the floodlight activities list request. - activities = reporting.floodlightActivities().list(profileId).setAdvertiserId(advertiserId) - .setFields(fields).setPageToken(nextPageToken).execute(); - - for (FloodlightActivity activity : activities.getFloodlightActivities()) { - System.out.printf("Floodlight activity with ID %d and name \"%s\" was found.%n", - activity.getId(), activity.getName()); - } - - // Update the next page token. - nextPageToken = activities.getNextPageToken(); - } while (!activities.getFloodlightActivities().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivityGroups.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivityGroups.java deleted file mode 100644 index 57a595f..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/floodlight/GetFloodlightActivityGroups.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.floodlight; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.FloodlightActivityGroup; -import com.google.api.services.dfareporting.model.FloodlightActivityGroupsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays floodlight activity groups for a given advertiser. - * - * To create an advertiser, run create_advertiser.py. - */ -public class GetFloodlightActivityGroups { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "floodlightActivityGroups(id,name)"; - - // Create and execute the floodlight activity groups list request. - FloodlightActivityGroupsListResponse groups = reporting.floodlightActivityGroups() - .list(profileId).setAdvertiserId(advertiserId).setFields(fields).execute(); - - for (FloodlightActivityGroup group : groups.getFloodlightActivityGroups()) { - System.out.printf("Floodlight activity group with ID %d and name \"%s\" was found.%n", - group.getId(), group.getName()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/CreateReportGuide.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/CreateReportGuide.java deleted file mode 100644 index fb8bcde..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/CreateReportGuide.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.guides; - -import com.google.api.client.util.DateTime; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CompatibleFields; -import com.google.api.services.dfareporting.model.DateRange; -import com.google.api.services.dfareporting.model.Dimension; -import com.google.api.services.dfareporting.model.DimensionValue; -import com.google.api.services.dfareporting.model.DimensionValueList; -import com.google.api.services.dfareporting.model.DimensionValueRequest; -import com.google.api.services.dfareporting.model.Metric; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportCompatibleFields; -import com.google.api.services.dfareporting.model.SortedDimension; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.util.Calendar; -import java.util.List; - -/** - * This example provides an end-to-end example of how to create and configure a standard report. - */ -public class CreateReportGuide { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - // 1. Create a report resource - Report report = createReportResource(); - - // 2. Define the report criteria - defineReportCriteria(report); - - // 3. (optional) Look up compatible fields - findCompatibleFields(reporting, profileId, report); - - // 4. Add dimension filters to the report criteria - addDimensionFilters(reporting, profileId, report); - - // 5. Save the report resource - report = insertReportResource(reporting, profileId, report); - } - - private static Report createReportResource() { - Report report = new Report(); - - // Set the required fields "name" and "type". - report.setName("Example standard report"); - report.setType("STANDARD"); - - // Set optional fields - report.setFileName("example_report"); - report.setFormat("CSV"); - - System.out.printf("Creating %s report resource with name \"%s\".%n", report.getType(), - report.getName()); - - return report; - } - - private static void defineReportCriteria(Report report) throws IOException { - // Define a date range to report on. This example uses explicit start and end dates to mimic - // the "LAST_MONTH" relative date range. - DateRange dateRange = new DateRange(); - dateRange.setEndDate(new DateTime(true, System.currentTimeMillis(), null)); - - Calendar lastMonth = Calendar.getInstance(); - lastMonth.add(Calendar.MONTH, -1); - dateRange.setStartDate(new DateTime(true, lastMonth.getTimeInMillis(), null)); - - // Create a report criteria. - Report.Criteria criteria = new Report.Criteria(); - criteria.setDateRange(dateRange); - criteria.setDimensions(Lists.newArrayList(new SortedDimension().setName("advertiser"))); - criteria.setMetricNames(Lists.newArrayList("clicks", "impressions")); - - // Add the criteria to the report resource. - report.setCriteria(criteria); - - System.out.printf("%nAdded report criteria:%n%s%n", criteria.toPrettyString()); - } - - private static void findCompatibleFields(Dfareporting reporting, long profileId, Report report) - throws IOException { - CompatibleFields fields = reporting.reports().compatibleFields() - .query(profileId, report).execute(); - - ReportCompatibleFields reportFields = fields.getReportCompatibleFields(); - - if (!reportFields.getDimensions().isEmpty()) { - // Add a compatible dimension to the report. - Dimension dimension = reportFields.getDimensions().get(0); - SortedDimension sortedDimension = new SortedDimension().setName(dimension.getName()); - report.getCriteria().getDimensions().add(sortedDimension); - } else if (!reportFields.getMetrics().isEmpty()) { - // Add a compatible metric to the report. - Metric metric = reportFields.getMetrics().get(0); - report.getCriteria().getMetricNames().add(metric.getName()); - } - - System.out.printf("%nUpdated report criteria (with compatible fields):%n%s%n", - report.getCriteria().toPrettyString()); - } - - private static void addDimensionFilters(Dfareporting reporting, long profileId, Report report) - throws IOException { - // Query advertiser dimension values for report run dates. - DimensionValueRequest request = new DimensionValueRequest(); - request.setStartDate(report.getCriteria().getDateRange().getStartDate()); - request.setEndDate(report.getCriteria().getDateRange().getEndDate()); - request.setDimensionName("advertiser"); - - DimensionValueList values = reporting.dimensionValues().query(profileId, request).execute(); - - if (!values.getItems().isEmpty()) { - // Add a value as a filter to the report criteria. - List filters = Lists.newArrayList(values.getItems().get(0)); - report.getCriteria().setDimensionFilters(filters); - } - - System.out.printf("%nUpdated report criteria (with valid dimension filters):%n%s%n", - report.getCriteria()); - } - - private static Report insertReportResource(Dfareporting reporting, long profileId, Report report) - throws IOException { - Report insertedReport = reporting.reports().insert(profileId, report).execute(); - - System.out.printf("%nSuccessfully inserted new report with ID %d.%n", insertedReport.getId()); - return insertedReport; - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/DownloadReportGuide.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/DownloadReportGuide.java deleted file mode 100644 index 6e80b75..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/DownloadReportGuide.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.guides; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.Files.Get; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.FileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.base.Strings; -import com.google.common.io.Files; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * This example provides an end-to-end example of how to find and download a report file. - */ -public class DownloadReportGuide { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "INSERT_REPORT_ID_HERE"; - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - // 1. Find a file to download - File file = findFile(reporting, profileId, reportId); - - if (file != null) { - // 2. (optional) Generate browser URL - generateBrowserUrl(reporting, reportId, file.getId()); - - // 3. Directly download the file - directDownloadFile(reporting, reportId, file.getId()); - } else { - System.out.printf("No file found for profile ID %s and report ID %d.%n", profileId, reportId); - } - } - - private static File findFile(Dfareporting reporting, long profileId, long reportId) - throws IOException { - File target = null; - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - files = reporting.reports().files().list(profileId, reportId).setPageToken(nextPageToken) - .execute(); - - for (File file : files.getItems()) { - if (isTargetFile(file)) { - target = file; - break; - } - } - - // Update the next page token. - nextPageToken = files.getNextPageToken(); - } while (target == null - && !files.getItems().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - - if (target != null) { - System.out.printf("Found file %d with filename \"%s\".%n", target.getId(), - target.getFileName()); - return target; - } - - System.out.printf("Unable to find file for profile ID %d and report ID %d.%n", profileId, - reportId); - return null; - } - - private static boolean isTargetFile(File file) { - // Provide custom validation logic here. - // For example purposes, any file with REPORT_AVAILABLE status is considered valid. - return "REPORT_AVAILABLE".equals(file.getStatus()); - } - - private static String generateBrowserUrl(Dfareporting reporting, long reportId, long fileId) - throws IOException { - File file = reporting.files().get(reportId, fileId).execute(); - String browserUrl = file.getUrls().getBrowserUrl(); - - System.out.printf("File %d has browser URL: %s.%n", file.getId(), browserUrl); - return browserUrl; - } - - private static void directDownloadFile(Dfareporting reporting, long reportId, long fileId) - throws IOException { - // Retrieve the file metadata. - File file = reporting.files().get(reportId, fileId).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // Prepare a local file to download the report contents to. - java.io.File outFile = new java.io.File(Files.createTempDir(), generateFileName(file)); - - // Create a get request. - Get getRequest = reporting.files().get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.getMediaHttpDownloader().setChunkSize(MediaHttpDownloader.MAXIMUM_CHUNK_SIZE); - - // Execute the get request and download the file. - try (OutputStream stream = new FileOutputStream(outFile)) { - getRequest.executeMediaAndDownloadTo(stream); - } - - System.out.printf("File %d downloaded to %s%n", file.getId(), outFile.getAbsolutePath()); - } - } - - private static String generateFileName(File file) { - // If no filename is specified, use the file ID instead. - String fileName = file.getFileName(); - if (Strings.isNullOrEmpty(fileName)) { - fileName = file.getId().toString(); - } - - String extension = "CSV".equals(file.getFormat()) ? ".csv" : ".xls"; - - return fileName + extension; - } -} - diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/FindAndRunReportGuide.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/FindAndRunReportGuide.java deleted file mode 100644 index 9196493..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/guides/FindAndRunReportGuide.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.guides; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.base.Strings; -import java.io.IOException; - -/** - * This example provides an end-to-end example of how to find and run a report. - */ -public class FindAndRunReportGuide { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - // 1. Find a report to run - Report report = findReport(reporting, profileId); - - if (report != null) { - // 2. Run the report - File file = runReport(reporting, profileId, report.getId()); - - // 3. Wait for the report file to be ready - file = waitForReportFile(reporting, report.getId(), file.getId()); - } else { - System.out.printf("No report found for profile ID %d.%n", profileId); - } - } - - private static Report findReport(Dfareporting reporting, long profileId) - throws IOException { - Report target = null; - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the reports list request. - reports = reporting.reports().list(profileId).setPageToken(nextPageToken).execute(); - - for (Report report : reports.getItems()) { - if (isTargetReport(report)) { - target = report; - break; - } - } - - // Update the next page token. - nextPageToken = reports.getNextPageToken(); - } while (target == null - && !reports.getItems().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - - if (target != null) { - System.out.printf("Found report %d with name \"%s\".%n", target.getId(), target.getName()); - return target; - } - - System.out.printf("Unable to find report for profile ID %d.%n", profileId); - return null; - } - - @SuppressWarnings("unused") - private static boolean isTargetReport(Report report) { - // Provide custom validation logic here. - // For example purposes, any report is considered valid. - return true; - } - - private static File runReport(Dfareporting reporting, long profileId, long reportId) - throws IOException { - // Run the report. - File file = reporting.reports().run(profileId, reportId).execute(); - - System.out.printf( - "Running report %d, current file status is %s.%n", reportId, file.getStatus()); - return file; - } - - private static File waitForReportFile(Dfareporting reporting, long reportId, - long fileId) throws IOException, InterruptedException { - BackOff backOff = - new ExponentialBackOff.Builder() - .setInitialIntervalMillis(10 * 1000) // 10 second initial retry - .setMaxIntervalMillis(10 * 60 * 1000) // 10 minute maximum retry - .setMaxElapsedTimeMillis(60 * 60 * 1000) // 1 hour total retry - .build(); - - do { - File file = reporting.files().get(reportId, fileId).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // File has finished processing. - System.out.printf("File status is %s, ready to download.%n", file.getStatus()); - return file; - } else if (!"PROCESSING".equals(file.getStatus())) { - // File failed to process. - System.out.printf("File status is %s, processing failed.", file.getStatus()); - return null; - } - - // The file hasn't finished processing yet, wait before checking again. - long retryInterval = backOff.nextBackOffMillis(); - if (retryInterval == BackOff.STOP) { - System.out.println("File processing deadline exceeded.%n"); - return null; - } - - System.out.printf("File status is %s, sleeping for %dms.%n", file.getStatus(), retryInterval); - Thread.sleep(retryInterval); - } while (true); - } -} - diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetChangeLogsForAdvertiser.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetChangeLogsForAdvertiser.java deleted file mode 100644 index cc277da..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetChangeLogsForAdvertiser.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.misc; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ChangeLog; -import com.google.api.services.dfareporting.model.ChangeLogsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example displays the change logs of a specified advertiser object. - * - * A similar pattern can be applied to get change logs for many other object types. - */ -public class GetChangeLogsForAdvertiser { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,changeLogs(action,fieldName,oldValue,newValue)"; - - ChangeLogsListResponse changeLogs; - String nextPageToken = null; - - do { - // Create and execute the change logs list request - changeLogs = reporting.changeLogs().list(profileId) - .setObjectIds(ImmutableList.of(advertiserId)).setObjectType("OBJECT_ADVERTISER") - .setFields(fields).setPageToken(nextPageToken).execute(); - - for (ChangeLog changeLog : changeLogs.getChangeLogs()) { - System.out.printf("%s: Field \"%s\" from \"%s\" to \"%s\".%n", changeLog.getAction(), - changeLog.getFieldName(), changeLog.getOldValue(), changeLog.getNewValue()); - } - - // Update the next page token. - nextPageToken = changeLogs.getNextPageToken(); - } while (!changeLogs.getChangeLogs().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSites.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSites.java deleted file mode 100755 index fe565a9..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSites.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.misc; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Site; -import com.google.api.services.dfareporting.model.SitesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example lists all existing sites. - */ -public class GetSites { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,sites(id,keyName)"; - - SitesListResponse sites; - String nextPageToken = null; - - do { - // Create and execute the sites list request. - sites = - reporting.sites().list(profileId).setFields(fields).setPageToken(nextPageToken).execute(); - - for (Site site : sites.getSites()) { - System.out.printf("Found site with ID %d and key name \"%s\".%n", site.getId(), - site.getKeyName()); - } - - // Update the next page token. - nextPageToken = sites.getNextPageToken(); - } while (!sites.getSites().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSize.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSize.java deleted file mode 100644 index 0d5e339..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/misc/GetSize.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.misc; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.dfareporting.model.SizesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all sizes for a given width and height. - */ -public class GetSize { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String HEIGHT = "ENTER_HEIGHT_HERE"; - private static final String WIDTH = "ENTER_WIDTH_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, int height, int width) - throws Exception { - // Create and execute the sizes list request. - SizesListResponse sizes = - reporting.sizes().list(profileId).setHeight(height).setWidth(width).execute(); - - for (Size size : sizes.getSizes()) { - System.out.printf("Found size with ID %d.%n", size.getId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - int height = Integer.parseInt(HEIGHT); - int width = Integer.parseInt(WIDTH); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, height, width); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreateContentCategory.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreateContentCategory.java deleted file mode 100644 index aa99d9f..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreateContentCategory.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ContentCategory; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a content category with the given name and description. - */ -public class CreateContentCategory { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CONTENT_CATEGORY_NAME = "INSERT_CONTENT_CATEGORY_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String contentCategoryName) - throws Exception { - // Create the content category. - ContentCategory contentCategory = new ContentCategory(); - contentCategory.setName(contentCategoryName); - - // Insert the content category. - ContentCategory result = - reporting.contentCategories().insert(profileId, contentCategory).execute(); - - // Display the new content category ID. - System.out.printf("Content category with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, CONTENT_CATEGORY_NAME); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacement.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacement.java deleted file mode 100644 index cbdadbc..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacement.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.Placement; -import com.google.api.services.dfareporting.model.PricingSchedule; -import com.google.api.services.dfareporting.model.Size; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example creates a placement in a given campaign. Requires a DFA site ID and ID of the - * campaign in which the placement will be created. To create a campaign, run CreateCampaign.java. - * To get a DFA site ID, run GetSite.java. To get a size ID, run GetSize.java. - */ -public class CreatePlacement { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String DFA_SITE_ID = "INSERT_SITE_ID_HERE"; - private static final String PLACEMENT_NAME = "INSERT_PLACEMENT_NAME_HERE"; - private static final String SIZE_ID = "INSERT_SIZE_ID_HERE"; - - - public static void runExample(Dfareporting reporting, long profileId, String placementName, - long dfaSiteId, long campaignId, long sizeId) throws Exception { - // Retrieve the campaign. - Campaign campaign = reporting.campaigns().get(profileId, campaignId).execute(); - - // Create the placement. - Placement placement = new Placement(); - placement.setName(placementName); - placement.setCampaignId(campaignId); - placement.setCompatibility("DISPLAY"); - placement.setPaymentSource("PLACEMENT_AGENCY_PAID"); - placement.setSiteId(dfaSiteId); - placement.setTagFormats(ImmutableList.of("PLACEMENT_TAG_STANDARD")); - - // Set the size of the placement. - Size size = new Size(); - size.setId(sizeId); - placement.setSize(size); - - // Set the pricing schedule for the placement. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.setEndDate(campaign.getEndDate()); - pricingSchedule.setPricingType("PRICING_TYPE_CPM"); - pricingSchedule.setStartDate(campaign.getStartDate()); - placement.setPricingSchedule(pricingSchedule); - - // Insert the placement. - Placement result = reporting.placements().insert(profileId, placement).execute(); - - // Display the new placement ID. - System.out.printf("Placement with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long dfaSiteId = Long.parseLong(DFA_SITE_ID); - long sizeId = Long.parseLong(SIZE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, PLACEMENT_NAME, dfaSiteId, campaignId, sizeId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementGroup.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementGroup.java deleted file mode 100644 index ed0d046..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementGroup.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Campaign; -import com.google.api.services.dfareporting.model.PlacementGroup; -import com.google.api.services.dfareporting.model.PricingSchedule; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a placement group in a given campaign. Requires the DFA site ID and campaign - * ID in which the placement group will be created into. To create a campaign, run - * CreateCampaign.java. To get DFA site ID, run GetSite.java. - */ -public class CreatePlacementGroup { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "INSERT_CAMPAIGN_ID_HERE"; - private static final String DFA_SITE_ID = "INSERT_DFA_SITE_ID_HERE"; - private static final String PLACEMENT_GROUP_NAME = "INSERT_PLACEMENT_GROUP_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long dfaSiteId, - long campaignId, String placementGroupName) throws Exception { - // Retrieve the campaign. - Campaign campaign = reporting.campaigns().get(profileId, campaignId).execute(); - - // Create a pricing schedule. - PricingSchedule pricingSchedule = new PricingSchedule(); - pricingSchedule.setEndDate(campaign.getEndDate()); - pricingSchedule.setPricingType("PRICING_TYPE_CPM"); - pricingSchedule.setStartDate(campaign.getStartDate()); - - // Create the placement group. - PlacementGroup placementGroup = new PlacementGroup(); - placementGroup.setCampaignId(campaignId); - placementGroup.setName(placementGroupName); - placementGroup.setPlacementGroupType("PLACEMENT_PACKAGE"); - placementGroup.setPricingSchedule(pricingSchedule); - placementGroup.setSiteId(dfaSiteId); - - // Insert the placement. - PlacementGroup result = reporting.placementGroups().insert(profileId, placementGroup).execute(); - - // Display the new placement ID. - System.out.printf("Placement group with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long dfaSiteId = Long.parseLong(DFA_SITE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, dfaSiteId, campaignId, PLACEMENT_GROUP_NAME); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementStrategy.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementStrategy.java deleted file mode 100644 index 1aaccca..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/CreatePlacementStrategy.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.PlacementStrategy; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example creates a placement strategy with the given name. - */ -public class CreatePlacementStrategy { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String PLACEMENT_STRATEGY_NAME = "INSERT_PLACEMENT_STRATEGY_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, - String placementStrategyName) throws Exception { - // Create the placement strategy. - PlacementStrategy placementStrategy = new PlacementStrategy(); - placementStrategy.setName(placementStrategyName); - - // Insert the placement strategy. - PlacementStrategy result = - reporting.placementStrategies().insert(profileId, placementStrategy).execute(); - - // Display the new placement strategy ID. - System.out.printf("Placement strategy with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, PLACEMENT_STRATEGY_NAME); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/DownloadPlacementTags.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/DownloadPlacementTags.java deleted file mode 100755 index a1991ff..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/DownloadPlacementTags.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.Placements.Generatetags; -import com.google.api.services.dfareporting.model.PlacementTag; -import com.google.api.services.dfareporting.model.PlacementsGenerateTagsResponse; -import com.google.api.services.dfareporting.model.TagData; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; -import java.util.List; - -/** - * This example downloads HTML Tags for a given campaign and placement ID. To create campaigns, run - * CreateCampaign.java. To create placements, run CreatePlacement.java. - */ -public class DownloadPlacementTags { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String CAMPAIGN_ID = "ENTER_CAMPAIGN_ID_HERE"; - private static final String PLACEMENT_ID = "ENTER_PLACEMENT_ID_HERE"; - - // The tag formats to generate - private static final ImmutableList TAG_FORMATS = - ImmutableList.of( - "PLACEMENT_TAG_STANDARD", - "PLACEMENT_TAG_IFRAME_JAVASCRIPT", - "PLACEMENT_TAG_INTERNAL_REDIRECT"); - - public static void runExample(Dfareporting reporting, long profileId, long campaignId, - long placementId, List tagFormats) throws Exception { - // Generate the placement activity tags. - Generatetags request = reporting.placements().generatetags(profileId); - request.setCampaignId(campaignId); - request.setTagFormats(tagFormats); - request.setPlacementIds(ImmutableList.of(placementId)); - - PlacementsGenerateTagsResponse response = request.execute(); - - // Display the placement activity tags. - for (PlacementTag tag : response.getPlacementTags()) { - for (TagData tagData : tag.getTagDatas()) { - System.out.printf("%s:%n", tagData.getFormat()); - - if (tagData.getImpressionTag() != null) { - System.out.println(tagData.getImpressionTag()); - } - - if (tagData.getClickTag() != null) { - System.out.println(tagData.getClickTag()); - } - - System.out.printf("%n"); - } - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long campaignId = Long.parseLong(CAMPAIGN_ID); - long placementId = Long.parseLong(PLACEMENT_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, campaignId, placementId, TAG_FORMATS); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetContentCategories.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetContentCategories.java deleted file mode 100644 index 9219aef..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetContentCategories.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ContentCategoriesListResponse; -import com.google.api.services.dfareporting.model.ContentCategory; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all available content categories. - */ -public class GetContentCategories { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,contentCategories(id,name)"; - - ContentCategoriesListResponse categories; - String nextPageToken = null; - - do { - // Create and execute the content categories list request - categories = reporting.contentCategories().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (ContentCategory category : categories.getContentCategories()) { - System.out.printf("Found content category with ID %d and name \"%s\".%n", - category.getId(), category.getName()); - } - - // Update the next page token - nextPageToken = categories.getNextPageToken(); - } while (!categories.getContentCategories().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacementStrategies.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacementStrategies.java deleted file mode 100644 index 4867b1a..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacementStrategies.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.PlacementStrategiesListResponse; -import com.google.api.services.dfareporting.model.PlacementStrategy; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all available placement strategies. - */ -public class GetPlacementStrategies { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,placementStrategies(id,name)"; - - PlacementStrategiesListResponse strategies; - String nextPageToken = null; - - do { - // Create and execute the placement strategies list request. - strategies = reporting.placementStrategies().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (PlacementStrategy strategy : strategies.getPlacementStrategies()) { - System.out.printf("Placement strategy with ID %d and name \"%s\" was found.%n", - strategy.getId(), strategy.getName()); - } - - // Update the next page token. - nextPageToken = strategies.getNextPageToken(); - } while (!strategies.getPlacementStrategies().isEmpty() - && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacements.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacements.java deleted file mode 100644 index c310859..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/placements/GetPlacements.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.placements; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Placement; -import com.google.api.services.dfareporting.model.PlacementsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all available placements. - */ -public class GetPlacements { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,placements(campaignId,id,name)"; - - PlacementsListResponse placements; - String nextPageToken = null; - - do { - // Create and execute the placements list request. - placements = reporting.placements().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Placement placement : placements.getPlacements()) { - System.out.printf( - "Placement with ID %d and name \"%s\" is associated with campaign ID %d.%n", - placement.getId(), placement.getName(), placement.getCampaignId()); - } - - // Update the next page token. - nextPageToken = placements.getNextPageToken(); - } while (!placements.getPlacements().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/CreateRemarketingList.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/CreateRemarketingList.java deleted file mode 100644 index eceb8d0..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/CreateRemarketingList.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.ListPopulationClause; -import com.google.api.services.dfareporting.model.ListPopulationRule; -import com.google.api.services.dfareporting.model.ListPopulationTerm; -import com.google.api.services.dfareporting.model.RemarketingList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example creates a remarketing list for a given advertiser and floodlight activity, using a - * custom rule. - * - * Note: this sample assumes that the floodlight activity specified has a U1 custom floodlight - * variable. - */ -public class CreateRemarketingList { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - private static final String FLOODLIGHT_ACTIVITY_ID = "ENTER_FLOODLIGHT_ACTIVITY_ID_HERE"; - private static final String REMARKETING_LIST_NAME = "ENTER_REMARKETING_LIST_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String remaketingListName, - long advertiserId, long floodlightActivityId) throws Exception { - // Create the remarketing list. - RemarketingList remarketingList = new RemarketingList(); - remarketingList.setActive(true); - remarketingList.setAdvertiserId(advertiserId); - remarketingList.setLifeSpan(30L); // Set the membership lifespan to 30 days. - remarketingList.setName(remaketingListName); - - // Create a list population term. - // This term matches all visitors with a U1 value exactly matching "test_value". - ListPopulationTerm term = new ListPopulationTerm(); - term.setOperator("STRING_EQUALS"); - term.setType("CUSTOM_VARIABLE_TERM"); - term.setValue("test_value"); - term.setVariableName("U1"); - - // Add the term to a list population clause. - ListPopulationClause clause = new ListPopulationClause(); - clause.setTerms(ImmutableList.of(term)); - - // Add the clause to a list population rule. - // This rule will target all visitors who trigger the specified floodlight activity and satisfy - // the custom rule defined in the list population term. - ListPopulationRule rule = new ListPopulationRule(); - rule.setFloodlightActivityId(floodlightActivityId); - rule.setListPopulationClauses(ImmutableList.of(clause)); - remarketingList.setListPopulationRule(rule); - - // Insert the remarketing list. - RemarketingList result = - reporting.remarketingLists().insert(profileId, remarketingList).execute(); - - // Display the new remarketing list ID. - System.out.printf("Remarketing list with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long floodlightActivityId = Long.parseLong(FLOODLIGHT_ACTIVITY_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, REMARKETING_LIST_NAME, advertiserId, floodlightActivityId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/GetRemarketingLists.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/GetRemarketingLists.java deleted file mode 100644 index a90baa8..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/GetRemarketingLists.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.RemarketingList; -import com.google.api.services.dfareporting.model.RemarketingListsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all remarketing lists owned by the specified advertiser. - * - * Note: the RemarketingLists resource will only return lists owned by the specified advertiser. To - * see all lists that can be used for targeting ads (including those shared from other accounts or - * advertisers), use the TargetableRemarketingLists resource instead. - */ -public class GetRemarketingLists { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,remarketingLists(accountId,advertiserId,id,name)"; - - RemarketingListsListResponse lists; - String nextPageToken = null; - - do { - // Create and execute the remarketing list request. - lists = reporting.remarketingLists().list(profileId, advertiserId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (RemarketingList list : lists.getRemarketingLists()) { - System.out.printf("Remarketing list with ID %d and name \"%s\" was found.%n", - list.getId(), list.getName()); - } - - // Update the next page token. - nextPageToken = lists.getNextPageToken(); - } while (!lists.getRemarketingLists().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/ShareRemarketingListToAdvertiser.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/ShareRemarketingListToAdvertiser.java deleted file mode 100644 index e76f607..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/ShareRemarketingListToAdvertiser.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.RemarketingListShare; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.base.Joiner; - -import java.util.ArrayList; - -/** - * This example shares an existing remarketing list with the specified advertiser. - */ -public class ShareRemarketingListToAdvertiser { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "ENTER_ADVERTISER_ID_HERE"; - private static final String REMARKETING_LIST_ID = "ENTER_REMARKETING_LIST_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long advertiserId, - long remarketingListId) throws Exception { - // Load the existing share info. - RemarketingListShare share = - reporting.remarketingListShares().get(profileId, remarketingListId).execute(); - - if (share.getSharedAdvertiserIds() == null) { - share.setSharedAdvertiserIds(new ArrayList()); - } - - if (!share.getSharedAdvertiserIds().contains(advertiserId)) { - share.getSharedAdvertiserIds().add(advertiserId); - - // Update the share info with the newly added advertiser ID. - RemarketingListShare result = - reporting.remarketingListShares().update(profileId, share).execute(); - - String sharedAdvertiserIds = Joiner.on(", ").join(result.getSharedAdvertiserIds()); - System.out.printf("Remarketing list with ID %s is now shared to advertiser ID(s): %s.%n", - result.getRemarketingListId(), sharedAdvertiserIds); - } else { - System.out.printf("Remarketing list with ID %d is already shared to advertiser ID %d.%n", - remarketingListId, advertiserId); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - long remarketingListId = Long.parseLong(REMARKETING_LIST_ID); - - runExample(reporting, profileId, advertiserId, remarketingListId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/TargetAdToRemarketingList.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/TargetAdToRemarketingList.java deleted file mode 100644 index c8fb06d..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/remarketing/TargetAdToRemarketingList.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.remarketing; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Ad; -import com.google.api.services.dfareporting.model.ListTargetingExpression; -import com.google.api.services.dfareporting.model.TargetableRemarketingList; -import com.google.api.services.dfareporting.model.TargetableRemarketingListsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example targets an ad to a remarketing list. - * - * The first targetable remarketing list, either owned by or shared to the ad's advertiser, will be - * used. To create a remarketing list, see CreateRemarketingList.java. To share a remarketing list - * with the ad's advertiser, see ShareRemarketingListToAdvertiser.java. - */ -public class TargetAdToRemarketingList { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String AD_ID = "ENTER_AD_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long adId) - throws Exception { - Ad ad = reporting.ads().get(profileId, adId).execute(); - - TargetableRemarketingListsListResponse lists = reporting.targetableRemarketingLists() - .list(profileId, ad.getAdvertiserId()).setMaxResults(1).execute(); - - if (!lists.getTargetableRemarketingLists().isEmpty()) { - // Select the first targetable remarketing list that was returned. - TargetableRemarketingList list = lists.getTargetableRemarketingLists().get(0); - - // Create a list targeting expression. - ListTargetingExpression expression = new ListTargetingExpression(); - expression.setExpression(list.getId().toString()); - - // Update the ad. - ad.setRemarketingListExpression(expression); - Ad result = reporting.ads().update(profileId, ad).execute(); - - System.out.printf("Ad with ID %d updated to use remarketing list expression: \"%s\".%n", - result.getId(), result.getRemarketingListExpression().getExpression()); - } else { - System.out.printf("No targetable remarketing lists found for ad with ID %d", adId); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long adId = Long.parseLong(AD_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, adId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/CreateReport.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/CreateReport.java deleted file mode 100644 index 71f79b4..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/CreateReport.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.DateRange; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.Report.Criteria; -import com.google.api.services.dfareporting.model.SortedDimension; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example illustrates how to create a report. - */ -public class CreateReport { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_NAME = "INSERT_REPORT_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String reportName) - throws Exception { - // Create a date range to report on. - DateRange dateRange = new DateRange(); - dateRange.setRelativeDateRange("YESTERDAY"); - - // Create a dimension to report on. - SortedDimension dimension = new SortedDimension(); - dimension.setName("campaign"); - - // Create the criteria for the report. - Criteria criteria = new Criteria(); - criteria.setDateRange(dateRange); - criteria.setDimensions(ImmutableList.of(dimension)); - criteria.setMetricNames(ImmutableList.of("clicks")); - - // Create the report. - Report report = new Report(); - report.setCriteria(criteria); - report.setName(reportName); - report.setType("STANDARD"); - - // Insert the report. - Report result = reporting.reports().insert(profileId, report).execute(); - - // Display the new report ID. - System.out.printf("Standard report with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, REPORT_NAME); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/DeleteReport.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/DeleteReport.java deleted file mode 100644 index dfc21d5..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/DeleteReport.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to delete a report. - */ -public class DeleteReport { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "INSERT_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Delete the report. - reporting.reports().delete(profileId, reportId).execute(); - - // Display the new report ID. - System.out.printf("Report with ID %d was successfully deleted.%n", reportId); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/DownloadFile.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/DownloadFile.java deleted file mode 100644 index 63c8a7d..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/DownloadFile.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.Dfareporting.Files.Get; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import com.google.common.base.Strings; -import com.google.common.io.Files; -import java.io.FileOutputStream; -import java.io.OutputStream; - -/** - * This example illustrates how to download a file. - */ -public class DownloadFile { - private static final String FILE_ID = "ENTER_FILE_ID_HERE"; - private static final String REPORT_ID = "ENTER_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long reportId, long fileId) - throws Exception { - // Retrieve the file metadata. - File file = reporting.files().get(reportId, fileId).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // Prepare a local file to download the report contents to. - java.io.File outFile = new java.io.File(Files.createTempDir(), generateFileName(file)); - - // Create a get request. - Get getRequest = reporting.files().get(reportId, fileId); - - // Optional: adjust the chunk size used when downloading the file. - // getRequest.getMediaHttpDownloader().setChunkSize(MediaHttpDownloader.MAXIMUM_CHUNK_SIZE); - - // Execute the get request and download the file. - try (OutputStream stream = new FileOutputStream(outFile)) { - getRequest.executeMediaAndDownloadTo(stream); - } - - System.out.printf("File %d downloaded to %s%n", file.getId(), outFile.getAbsolutePath()); - } - } - - private static String generateFileName(File file) { - // If no filename is specified, use the file ID instead. - String fileName = file.getFileName(); - if (Strings.isNullOrEmpty(fileName)) { - fileName = file.getId().toString(); - } - - String extension = "CSV".equals(file.getFormat()) ? ".csv" : ".xls"; - - return fileName + extension; - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long fileId = Long.parseLong(FILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, reportId, fileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetCompatibleFields.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetCompatibleFields.java deleted file mode 100644 index e6db886..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetCompatibleFields.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.CompatibleFields; -import com.google.api.services.dfareporting.model.Dimension; -import com.google.api.services.dfareporting.model.Metric; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportCompatibleFields; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import java.util.List; - -/** - * This example illustrates how to get the compatible fields for a standard report. - */ -public class GetCompatibleFields { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "ENTER_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Retrieve the specified report. - Report report = reporting.reports().get(profileId, reportId).execute(); - - // Look up the compatible fields for the report. - CompatibleFields fields = - reporting.reports().compatibleFields().query(profileId, report).execute(); - - // Display the compatible fields, assuming this is a standard report. - ReportCompatibleFields reportFields = fields.getReportCompatibleFields(); - - System.out.println("Compatible dimensions:"); - printDimensionNames(reportFields.getDimensions()); - - System.out.printf("%nCompatible metrics:%n"); - printMetricNames(reportFields.getMetrics()); - - System.out.printf("%nCompatible dimension filters:%n"); - printDimensionNames(reportFields.getDimensionFilters()); - - System.out.printf("%nCompatible pivoted activity metrics:%n"); - printMetricNames(reportFields.getPivotedActivityMetrics()); - } - - private static void printDimensionNames(List dimensions) { - for (Dimension dimension : dimensions) { - System.out.println(dimension.getName()); - } - } - - private static void printMetricNames(List metrics) { - for (Metric metric : metrics) { - System.out.println(metric.getName()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetDimensionValues.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetDimensionValues.java deleted file mode 100644 index fa35d90..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetDimensionValues.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.DateTime; -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.DimensionValue; -import com.google.api.services.dfareporting.model.DimensionValueList; -import com.google.api.services.dfareporting.model.DimensionValueRequest; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -import java.util.Calendar; - -/** - * This example illustrates how to get all dimension values for a dimension. - */ -public class GetDimensionValues { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(id,value)"; - - // Construct the dimension value request. - DimensionValueRequest request = new DimensionValueRequest(); - request.setDimensionName("advertiser"); - - // Set the date range from 1 year ago until today. - Calendar today = Calendar.getInstance(); - Calendar lastYear = Calendar.getInstance(); - lastYear.add(Calendar.YEAR, -1); - - request.setStartDate(new DateTime(true, lastYear.getTimeInMillis(), null)); - request.setEndDate(new DateTime(true, today.getTimeInMillis(), null)); - - DimensionValueList values; - String nextPageToken = null; - - do { - // Create and execute the dimension value query request. - values = reporting.dimensionValues().query(profileId, request).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (DimensionValue value : values.getItems()) { - System.out.printf("Dimension value with ID %s and value \"%s\" was found.%n", - value.getId(), value.getValue()); - } - - // Update the next page token. - nextPageToken = values.getNextPageToken(); - } while (!values.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetFiles.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetFiles.java deleted file mode 100644 index 85155f8..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetFiles.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.FileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all the files for a profile. - */ -public class GetFiles { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the files list request. - files = - reporting.files().list(profileId).setFields(fields).setPageToken(nextPageToken).execute(); - - for (File file : files.getItems()) { - System.out.printf("Report file with ID %d and file name \"%s\" has status \"%s\".%n", - file.getId(), file.getFileName(), file.getStatus()); - } - - // Update the next page token. - nextPageToken = files.getNextPageToken(); - } while (!files.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReportFiles.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReportFiles.java deleted file mode 100644 index 9cdced7..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReportFiles.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.dfareporting.model.FileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all the files for a report. - */ -public class GetReportFiles { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "ENTER_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(fileName,id,status)"; - - FileList files; - String nextPageToken = null; - - do { - // Create and execute the report files list request. - files = reporting.reports().files().list(profileId, reportId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (File file : files.getItems()) { - System.out.printf("Report file with ID %d and file name \"%s\" has status \"%s\".%n", - file.getId(), file.getFileName(), file.getStatus()); - } - - // Update the next page token. - nextPageToken = files.getNextPageToken(); - } while (!files.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReports.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReports.java deleted file mode 100644 index 5bb6cd7..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/GetReports.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Report; -import com.google.api.services.dfareporting.model.ReportList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all reports. - */ -public class GetReports { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,items(id,name,type)"; - - ReportList reports; - String nextPageToken = null; - - do { - // Create and execute the report list request. - reports = reporting.reports().list(profileId).setFields(fields).setPageToken(nextPageToken) - .execute(); - - for (Report report : reports.getItems()) { - System.out.printf("%s report with ID %d and name \"%s\" was found.%n", report.getType(), - report.getId(), report.getName()); - } - - // Update the next page token. - nextPageToken = reports.getNextPageToken(); - } while (!reports.getItems().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/RunReport.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/RunReport.java deleted file mode 100644 index c627916..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/reports/RunReport.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.reports; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.File; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to run a report. - */ -public class RunReport { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String REPORT_ID = "INSERT_REPORT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long reportId) - throws Exception { - // Run the report. - File file = reporting.reports().run(profileId, reportId).execute(); - System.out.printf("File with ID %d has been created.%n", file.getId()); - - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve request quota. - BackOff backOff = - new ExponentialBackOff.Builder() - .setInitialIntervalMillis(10 * 1000) // 10 second initial retry - .setMaxIntervalMillis(10 * 60 * 1000) // 10 minute maximum retry - .setMaxElapsedTimeMillis(60 * 60 * 1000) // 1 hour total retry - .build(); - - do { - file = reporting.files().get(file.getReportId(), file.getId()).execute(); - - if ("REPORT_AVAILABLE".equals(file.getStatus())) { - // File has finished processing. - System.out.printf("File status is %s, ready to download.%n", file.getStatus()); - return; - } else if (!"PROCESSING".equals(file.getStatus())) { - // File failed to process. - System.out.printf("File status is %s, processing failed.", file.getStatus()); - return; - } - - // The file hasn't finished processing yet, wait before checking again. - long retryInterval = backOff.nextBackOffMillis(); - if (retryInterval == BackOff.STOP) { - System.out.println("File processing deadline exceeded.%n"); - return; - } - - System.out.printf("File status is %s, sleeping for %dms.%n", file.getStatus(), retryInterval); - Thread.sleep(retryInterval); - } while (true); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long reportId = Long.parseLong(REPORT_ID); - - runExample(reporting, profileId, reportId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/CreateSubaccount.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/CreateSubaccount.java deleted file mode 100644 index 6b70566..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/CreateSubaccount.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.subaccounts; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Subaccount; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -import java.util.List; - -/** - * This example creates a subaccount in a given DoubleClick Campaign Manager account. To get the - * available permissions, run GetSubaccountPermissions.java. - */ -public class CreateSubaccount { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ACCOUNT_ID = "INSERT_ACCOUNT_ID_HERE"; - private static final String PERMISSION_ONE = "INSERT_FIRST_PERMISSION_ID_HERE"; - private static final String PERMISSION_TWO = "INSERT_SECOND_PERMISSION_ID_HERE"; - private static final String SUBACCOUNT_NAME = "INSERT_SUBACCOUNT_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String subaccountName, - long accountId, long permissionOneId, long permissionTwoId) throws Exception { - // Create subaccount structure. - Subaccount subaccount = new Subaccount(); - subaccount.setName(subaccountName); - subaccount.setAccountId(accountId); - - // Create a collection of all permissions assigned to this subaccount and add it to the - // subaccount structure. To get list of available permissions, run GetUserRolePermissions.java. - List availablePermissionIds = ImmutableList.of(permissionOneId, permissionTwoId); - subaccount.setAvailablePermissionIds(availablePermissionIds); - - // Create subaccount. - Subaccount result = reporting.subaccounts().insert(profileId, subaccount).execute(); - - // Display subaccount ID. - System.out.printf("Subaccount with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long accountId = Long.parseLong(ACCOUNT_ID); - long permissionOneId = Long.parseLong(PERMISSION_ONE); - long permissionTwoId = Long.parseLong(PERMISSION_TWO); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, SUBACCOUNT_NAME, accountId, permissionOneId, permissionTwoId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccountPermissions.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccountPermissions.java deleted file mode 100644 index 8551837..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccountPermissions.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.subaccounts; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Subaccount; -import com.google.api.services.dfareporting.model.UserRolePermission; -import com.google.api.services.dfareporting.model.UserRolePermissionsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all of the available user role permissions for a specified - * subaccount. - * - * To get a subaccount ID, run GetSubaccounts.java. - */ -public class GetSubaccountPermissions { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - private static final String SUBACCOUNT_ID = "ENTER_SUBACCOUNT_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long subaccountId) - throws Exception { - // Limit the fields returned. - String fields = "userRolePermissions(id,name)"; - - // Retrieve the subaccount. - Subaccount subaccount = reporting.subaccounts().get(profileId, subaccountId).execute(); - - // Retrieve the subaccount permissions. - UserRolePermissionsListResponse permissions = reporting.userRolePermissions().list(profileId) - .setIds(subaccount.getAvailablePermissionIds()).setFields(fields).execute(); - - // Display the subaccount permissions. - for (UserRolePermission permission : permissions.getUserRolePermissions()) { - System.out.printf("User role permission with ID %d and name \"%s\" was found.%n", - permission.getId(), permission.getName()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - long subaccountId = Long.parseLong(SUBACCOUNT_ID); - - runExample(reporting, profileId, subaccountId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccounts.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccounts.java deleted file mode 100644 index 7d29d7b..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/subaccounts/GetSubaccounts.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.subaccounts; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Subaccount; -import com.google.api.services.dfareporting.model.SubaccountsListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all subaccounts. - * - * Note that the permissions assigned to a subaccount are not returned in a human-readable format - * with this example. Run GetSubaccountPermissions.java to see what permissions are available on a - * subaccount. - */ -public class GetSubaccounts { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,subaccounts(id,name)"; - - SubaccountsListResponse subaccounts; - String nextPageToken = null; - - do { - // Create and execute the subaccounts list request. - subaccounts = reporting.subaccounts().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (Subaccount subaccount : subaccounts.getSubaccounts()) { - System.out.printf("Subaccount with ID %d and name \"%s\" was found.%n", subaccount.getId(), - subaccount.getName()); - } - - // Update the next page token. - nextPageToken = subaccounts.getNextPageToken(); - } while (!subaccounts.getSubaccounts().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/ConfigureDynamicAssetSelection.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/ConfigureDynamicAssetSelection.java deleted file mode 100644 index ae1e7bd..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/ConfigureDynamicAssetSelection.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.targeting; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.Creative; -import com.google.api.services.dfareporting.model.CreativeAsset; -import com.google.api.services.dfareporting.model.CreativeAssetMetadata; -import com.google.api.services.dfareporting.model.CreativeAssetSelection; -import com.google.api.services.dfareporting.model.Rule; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.api.services.samples.dfareporting.creatives.assets.CreativeAssetUtils; - -import java.util.ArrayList; - -/** - * This example uploads a new video asset to an existing in-stream video creative and configures - * dynamic asset selection, using a specified targeting template. To get an in-stream video - * creative, run CreateInstreamVideoCreative.java. To get a targeting template, run - * CreateTargetingTemplate.java. - */ -public class ConfigureDynamicAssetSelection { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String INSTREAM_VIDEO_CREATIVE_ID = "INSERT_INSTREAM_VIDEO_ASSET_ID_HERE"; - private static final String TARGETING_TEMPLATE_ID = "INSERT_TARGETING_TEMPLATE_ID_HERE"; - - // Video asset values - private static final String VIDEO_ASSET_NAME = "INSERT_VIDEO_ASSET_NAME_HERE"; - private static final String PATH_TO_VIDEO_ASSET_FILE = "INSERT_PATH_TO_VIDEO_ASSET_FILE_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, long creativeId, - long templateId, String videoAssetName, String pathToVideoAsset) throws Exception { - // Retrieve the specified creative. - Creative creative = reporting.creatives().get(profileId, creativeId).execute(); - if (creative == null || !"INSTREAM_VIDEO".equals(creative.getType())) { - System.out.println("Invalid creative specified."); - return; - } - - CreativeAssetSelection selection = creative.getCreativeAssetSelection(); - if (!creative.getDynamicAssetSelection()) { - // Locate an existing video asset to use as a default. - // This example uses the first PARENT_VIDEO asset found. - long defaultVideoAssetId = findDefaultVideoAssetId(creative); - if (defaultVideoAssetId < 0) { - System.out.println("Default video asset could not be found."); - return; - } - - // Create a new selection using the existing asset as a default. - selection = new CreativeAssetSelection(); - selection.setDefaultAssetId(defaultVideoAssetId); - selection.setRules(new ArrayList()); - - // Enable dynamic asset selection for the creative. - creative.setDynamicAssetSelection(true); - creative.setCreativeAssetSelection(selection); - } - - // Upload the new video asset and add it to the creative. - CreativeAssetMetadata videoAssetMetadata = CreativeAssetUtils.uploadAsset(reporting, profileId, - creative.getAdvertiserId(), videoAssetName, pathToVideoAsset, "VIDEO"); - creative.getCreativeAssets().add(new CreativeAsset() - .setAssetIdentifier(videoAssetMetadata.getAssetIdentifier()).setRole("PARENT_VIDEO")); - - // Create a rule targeting the new video asset and add it to the selection. - Rule rule = new Rule(); - rule.setAssetId(videoAssetMetadata.getId()); - rule.setName("Test rule for asset " + videoAssetMetadata.getId()); - rule.setTargetingTemplateId(templateId); - selection.getRules().add(rule); - - // Update the creative. - Creative result = reporting.creatives().update(profileId, creative).execute(); - System.out.printf("Dynamic asset selection enabled for creative with ID %d.%n", - result.getId()); - } - - private static long findDefaultVideoAssetId(Creative creative) { - for (CreativeAsset asset : creative.getCreativeAssets()) { - if ("PARENT_VIDEO".equals(asset.getRole())) { - return asset.getId(); - } - } - - return -1; - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long creativeId = Long.parseLong(INSTREAM_VIDEO_CREATIVE_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - long templateId = Long.parseLong(TARGETING_TEMPLATE_ID); - - runExample(reporting, profileId, creativeId, templateId, VIDEO_ASSET_NAME, - PATH_TO_VIDEO_ASSET_FILE); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/CreateTargetingTemplate.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/CreateTargetingTemplate.java deleted file mode 100644 index 105c9ea..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/CreateTargetingTemplate.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.targeting; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.DayPartTargeting; -import com.google.api.services.dfareporting.model.TargetingTemplate; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -/** - * This example creates a basic targeting template associated with a given advertiser. To get an - * advertiser ID, run GetAdvertisers.java. - */ -public class CreateTargetingTemplate { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String ADVERTISER_ID = "INSERT_ADVERTISER_ID_HERE"; - private static final String TARGETING_TEMPLATE_NAME = "INSERT_TARGETING_TEMPLATE_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String templateName, - long advertiserId) throws Exception { - // Create the targeting template. - TargetingTemplate template = new TargetingTemplate(); - template.setAdvertiserId(advertiserId); - template.setName(templateName); - - // Configure the template to serve ads on Monday, Wednesday, and Friday from 9-10am and 3-5pm. - DayPartTargeting dayTargeting = new DayPartTargeting(); - dayTargeting.setDaysOfWeek(ImmutableList.of("MONDAY", "WEDNESDAY", "FRIDAY")); - dayTargeting.setHoursOfDay(ImmutableList.of(9, 15, 16)); - dayTargeting.setUserLocalTime(true); - template.setDayPartTargeting(dayTargeting); - - // Insert the targeting template. - TargetingTemplate result = - reporting.targetingTemplates().insert(profileId, template).execute(); - - // Display the new targeting template ID. - System.out.printf("Targeting template with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long advertiserId = Long.parseLong(ADVERTISER_ID); - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId, TARGETING_TEMPLATE_NAME, advertiserId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/GetTargetingTemplates.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/GetTargetingTemplates.java deleted file mode 100644 index ba1bdf8..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/targeting/GetTargetingTemplates.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2016 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.api.services.samples.dfareporting.targeting; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.TargetingTemplate; -import com.google.api.services.dfareporting.model.TargetingTemplatesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays the name, ID and advertiser ID for every targeting template your DCM user - * profile can see. - */ -public class GetTargetingTemplates { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,targetingTemplates(advertiserId,id,name)"; - - TargetingTemplatesListResponse result; - String nextPageToken = null; - - do { - // Create and execute the targeting templates list request. - result = reporting.targetingTemplates().list(profileId).setFields(fields) - .setPageToken(nextPageToken).execute(); - - for (TargetingTemplate template : result.getTargetingTemplates()) { - System.out.printf( - "Targeting template with ID %d and name \"%s\" is associated with advertiser ID %d.%n", - template.getId(), template.getName(), template.getAdvertiserId()); - } - - // Update the next page token. - nextPageToken = result.getNextPageToken(); - } while (!result.getTargetingTemplates().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userprofiles/GetUserProfiles.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userprofiles/GetUserProfiles.java deleted file mode 100644 index 114dc48..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userprofiles/GetUserProfiles.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.userprofiles; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.UserProfile; -import com.google.api.services.dfareporting.model.UserProfileList; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example illustrates how to get a list of all user profiles. - */ -public class GetUserProfiles { - public static void runExample(Dfareporting reporting) throws Exception { - // Retrieve and print all user profiles for the current authorized user. - UserProfileList profiles = reporting.userProfiles().list().execute(); - for (UserProfile profile : profiles.getItems()) { - System.out.printf("User profile with ID %d and name \"%s\" was found for account %d.%n", - profile.getProfileId(), profile.getUserName(), profile.getAccountId()); - } - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - runExample(reporting); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userroles/CreateUserRole.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userroles/CreateUserRole.java deleted file mode 100644 index 8baaa1f..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userroles/CreateUserRole.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.userroles; - -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.UserRole; -import com.google.api.services.dfareporting.model.UserRolePermission; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; -import com.google.common.collect.ImmutableList; - -import java.util.List; - -/** - * This example creates a user role in a given DoubleClick Campaign Manager subaccount. To get the - * subaccount ID, run GetSubaccounts.java. To get the available permissions, run - * GetUserRolePermissions.java. To get the parent user role ID, run GetUserRoles.java. - */ -public class CreateUserRole { - private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE"; - - private static final String PARENT_USER_ROLE_ID = "INSERT_PARENT_USER_ROLE_ID_HERE"; - private static final String PERMISSION_ID_ONE = "INSERT_FIRST_PERMISSION_ID_HERE"; - private static final String PERMISSION_ID_TWO = "INSERT_SECOND_PERMISSION_ID_HERE"; - private static final String SUBACCOUNT_ID = "INSERT_SUBACCOUNT_ID_HERE"; - private static final String USER_ROLE_NAME = "INSERT_USER_ROLE_NAME_HERE"; - - public static void runExample(Dfareporting reporting, long profileId, String userRoleName, - long subaccountId, long parentUserRoleId, long permission1Id, long permission2Id) - throws Exception { - // Create user role structure. - UserRole userRole = new UserRole(); - userRole.setName(userRoleName); - userRole.setSubaccountId(subaccountId); - userRole.setParentUserRoleId(parentUserRoleId); - - // Create a permission object to represent each permission this user role - // has. - UserRolePermission permission1 = new UserRolePermission(); - permission1.setId(permission1Id); - UserRolePermission permission2 = new UserRolePermission(); - permission2.setId(permission2Id); - List permissions = ImmutableList.of(permission1, permission2); - - // Add the permissions to the user role. - userRole.setPermissions(permissions); - - // Create user role. - UserRole result = reporting.userRoles().insert(profileId, userRole).execute(); - - // Display user role ID. - System.out.printf("User role with ID %d was created.%n", result.getId()); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long parentUserRoleId = Long.parseLong(PARENT_USER_ROLE_ID); - long permission1Id = Long.parseLong(PERMISSION_ID_ONE); - long permission2Id = Long.parseLong(PERMISSION_ID_TWO); - long profileId = Long.parseLong(USER_PROFILE_ID); - long subaccountId = Long.parseLong(SUBACCOUNT_ID); - - runExample(reporting, profileId, USER_ROLE_NAME, subaccountId, parentUserRoleId, permission1Id, - permission2Id); - } -} diff --git a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userroles/GetUserRoles.java b/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userroles/GetUserRoles.java deleted file mode 100755 index cdb0550..0000000 --- a/java/v3.5/src/main/java/com/google/api/services/samples/dfareporting/userroles/GetUserRoles.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.api.services.samples.dfareporting.userroles; - -import com.google.api.client.util.Strings; -import com.google.api.services.dfareporting.Dfareporting; -import com.google.api.services.dfareporting.model.UserRole; -import com.google.api.services.dfareporting.model.UserRolesListResponse; -import com.google.api.services.samples.dfareporting.DfaReportingFactory; - -/** - * This example displays all user roles. - * - * The output is limited to include only ID, name, account ID and subaccount ID. - */ -public class GetUserRoles { - private static final String USER_PROFILE_ID = "ENTER_USER_PROFILE_ID_HERE"; - - public static void runExample(Dfareporting reporting, long profileId) throws Exception { - // Limit the fields returned. - String fields = "nextPageToken,userRoles(accountId,id,name,subaccountId)"; - - UserRolesListResponse roles; - String nextPageToken = null; - - do { - // Create and execute the user roles list request. - roles = reporting.userRoles().list(profileId).setFields(fields).setPageToken(nextPageToken) - .execute(); - - for (UserRole role : roles.getUserRoles()) { - System.out.printf("User role with ID %d and name \"%s\" was found.%n", role.getId(), - role.getName()); - } - - // Update the next page token. - nextPageToken = roles.getNextPageToken(); - } while (!roles.getUserRoles().isEmpty() && !Strings.isNullOrEmpty(nextPageToken)); - } - - public static void main(String[] args) throws Exception { - Dfareporting reporting = DfaReportingFactory.getInstance(); - - long profileId = Long.parseLong(USER_PROFILE_ID); - - runExample(reporting, profileId); - } -} diff --git a/php/v3.4/README.md b/php/v3.4/README.md deleted file mode 100644 index 773cec4..0000000 --- a/php/v3.4/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# DCM/DFA Reporting and Trafficking API PHP Samples - -This is a collection of samples written in PHP which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - - - PHP 5.4+ - - JSON PHP extension - - Composer - -From the example directory, run `composer install` to install all dependencies. - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Overview screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" -> "OAuth2 client ID" - - Select "Web Application" as the "Application type" - - Configure javascript origins and redirect URIs - - Authorized Javascript Origins: http://localhost - - Authorized Redirect URIs: http://localhost/path/to/index.php - - Click "Create client ID" - - Click "Download JSON" and save the file as `client_secrets.json` in your - examples directory - -> #### Security alert! - -> Always ensure that your client_secrets.json file is not publicly accessible. -> This file contains credential information which could allow unauthorized access -> to your DFA account. - -## Running the Examples - -I'm assuming you've checked out the code and are reading this from a local -directory. If not check out the code to a local directory. - -1. Open the sample (`http://your/path/index.php`) in your browser - -2. Complete the authorization steps - -3. Select an example and provide the required information - -3. Examine the response, be inspired and start hacking an amazing new app! diff --git a/php/v3.4/auth/AuthenticateUsingServiceAccount.php b/php/v3.4/auth/AuthenticateUsingServiceAccount.php deleted file mode 100644 index aeb867a..0000000 --- a/php/v3.4/auth/AuthenticateUsingServiceAccount.php +++ /dev/null @@ -1,102 +0,0 @@ - - * - * This optional flag only applies to service accounts which have domain-wide - * delegation enabled and wish to make API requests on behalf of an account - * within that domain. Using this flag will not allow you to impersonate a user - * from a domain that you don't own (e.g., gmail.com). - */ -class AuthenticateUsingServiceAccount -{ - // The OAuth 2.0 scopes to request. - private static $OAUTH_SCOPES = [ - Google_Service_Dfareporting::DFAREPORTING - ]; - - public function run($pathToJsonFile, $email = null) - { - // Create an authenticated client object. - $client = $this->createAuthenticatedClient($pathToJsonFile, $email); - - // Create a Dfareporting service object. - $service = new Google_Service_Dfareporting($client); - - $this->getUserProfiles($service); - } - - private function createAuthenticatedClient($pathToJsonFile, $email) - { - // Create a Google_Client instance. - // - // Note: application name should be replaced with a value that identifies - // your application. Suggested format is "MyCompany-ProductName". - $client = new Google_Client(); - $client->setApplicationName('PHP service account sample'); - $client->setScopes(self::$OAUTH_SCOPES); - - // Load the service account credentials. - $client->setAuthConfig($pathToJsonFile); - - // Configure impersonation (if applicable). - if (!is_null($email)) { - $client->setSubject($email); - } - - return $client; - } - - private function getUserProfiles($service) - { - // Retrieve and print all user profiles for the current authorized user. - $result = $service->userProfiles->listUserProfiles(); - foreach ($result['items'] as $userProfile) { - printf( - "User profile \"%s\" (ID: %d) found for account %d.\n", - $userProfile->getUserName(), - $userProfile->getProfileId(), - $userProfile->getAccountId() - ); - } - } -} - -if ($argc < 2 || $argc >= 4) { - printf( - "Usage: %s /path/to/client_secrets.json [email_to_impersonate]\n", - $argv[0] - ); -} else { - $sample = new AuthenticateUsingServiceAccount(); - - if ($argc == 2) { - $sample->run($argv[1]); - } else { - $sample->run($argv[1], $argv[2]); - } -} diff --git a/php/v3.4/auth/AuthenticateUsingUserAccount.php b/php/v3.4/auth/AuthenticateUsingUserAccount.php deleted file mode 100644 index 0c3a003..0000000 --- a/php/v3.4/auth/AuthenticateUsingUserAccount.php +++ /dev/null @@ -1,110 +0,0 @@ -createAuthenticatedClient( - $pathToJsonFile, - self::TOKEN_STORE - ); - - // Create a Dfareporting service object. - $service = new Google_Service_Dfareporting($client); - - $this->getUserProfiles($service); - } - - private function createAuthenticatedClient($pathToJsonFile, $tokenStore) - { - // Create a Google_Client instance. - // - // Note: application name should be replaced with a value that identifies - // your application. Suggested format is "MyCompany-ProductName". - $client = new Google_Client(); - $client->setAccessType('offline'); - $client->setApplicationName('PHP installed app sample'); - $client->setRedirectUri(self::OAUTH_REDIRECT_URI); - $client->setScopes(self::$OAUTH_SCOPES); - - // Load the client secrets file. - $client->setAuthConfig($pathToJsonFile); - - // Try to load cached credentials from the token store. Using a token store - // allows auth credentials to be cached, so they survive multiple runs of - // the application. This avoids prompting the user for authorization every - // time the access token expires, by remembering the refresh token. - if (file_exists($tokenStore) && filesize($tokenStore) > 0) { - $client->setAccessToken(file_get_contents($tokenStore)); - } else { - // If no cached credentials were found, authorize and persist - // credentials to the token store. - print 'Open this URL in your browser and authorize the application.'; - printf("\n\n%s\n\n", $client->createAuthUrl()); - print 'Enter the authorization code: '; - $code = trim(fgets(STDIN)); - $client->authenticate($code); - - file_put_contents($tokenStore, json_encode($client->getAccessToken())); - } - - return $client; - } - - private function getUserProfiles($service) - { - // Retrieve and print all user profiles for the current authorized user. - $result = $service->userProfiles->listUserProfiles(); - foreach ($result['items'] as $userProfile) { - printf( - "User profile \"%s\" (ID: %d) found for account %d.\n", - $userProfile->getUserName(), - $userProfile->getProfileId(), - $userProfile->getAccountId() - ); - } - } -} - -if ($argc !== 2) { - printf("Usage: %s /path/to/client_secrets.json\n", $argv[0]); -} else { - $sample = new AuthenticateUsingUserAccount(); - $sample->run($argv[1]); -} diff --git a/php/v3.4/client_secrets.json b/php/v3.4/client_secrets.json deleted file mode 100755 index f29d5ac..0000000 --- a/php/v3.4/client_secrets.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "web": { - "client_id": "Enter Client ID", - "client_secret": "Enter Client Secret", - "redirect_uris": ["http://path/to/the/samples"] - } -} \ No newline at end of file diff --git a/php/v3.4/composer.json b/php/v3.4/composer.json deleted file mode 100755 index 801ab7f..0000000 --- a/php/v3.4/composer.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "require": { - "google/apiclient-services": "dev-master", - "google/apiclient": "^2.0", - "guzzlehttp/psr7": "^1.2" - } -} diff --git a/php/v3.4/composer.lock b/php/v3.4/composer.lock deleted file mode 100644 index 8c40b95..0000000 --- a/php/v3.4/composer.lock +++ /dev/null @@ -1,760 +0,0 @@ -{ - "_readme": [ - "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", - "This file is @generated automatically" - ], - "content-hash": "93032904091df2a7d0d6c4d31011cc65", - "packages": [ - { - "name": "firebase/php-jwt", - "version": "v3.0.0", - "source": { - "type": "git", - "url": "https://github.com/firebase/php-jwt.git", - "reference": "fa8a06e96526eb7c0eeaa47e4f39be59d21f16e1" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/firebase/php-jwt/zipball/fa8a06e96526eb7c0eeaa47e4f39be59d21f16e1", - "reference": "fa8a06e96526eb7c0eeaa47e4f39be59d21f16e1", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "autoload": { - "psr-4": { - "Firebase\\JWT\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Neuman Vong", - "email": "neuman+pear@twilio.com", - "role": "Developer" - }, - { - "name": "Anant Narayanan", - "email": "anant@php.net", - "role": "Developer" - } - ], - "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", - "homepage": "https://github.com/firebase/php-jwt", - "time": "2015-07-22T18:31:08+00:00" - }, - { - "name": "google/apiclient", - "version": "v2.0.1", - "source": { - "type": "git", - "url": "https://github.com/googleapis/google-api-php-client.git", - "reference": "984f6a96297242e901bde518489374a9dec209df" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-api-php-client/zipball/984f6a96297242e901bde518489374a9dec209df", - "reference": "984f6a96297242e901bde518489374a9dec209df", - "shasum": "" - }, - "require": { - "firebase/php-jwt": "~2.0|~3.0", - "google/apiclient-services": "*@dev", - "google/auth": "0.9", - "guzzlehttp/guzzle": "~5.2|~6.0", - "guzzlehttp/psr7": "^1.2", - "monolog/monolog": "^1.17", - "php": ">=5.4", - "phpseclib/phpseclib": "~2.0" - }, - "require-dev": { - "phpunit/phpunit": "~4", - "squizlabs/php_codesniffer": "~2.3", - "symfony/css-selector": "~2.1", - "symfony/dom-crawler": "~2.1", - "tedivm/stash": "^0.14.1" - }, - "suggest": { - "tedivm/stash": "For caching certs and tokens (using Google_Client::setCache)" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.x-dev" - } - }, - "autoload": { - "psr-0": { - "Google_": "src/" - }, - "classmap": [ - "src/Google/Service/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "Apache-2.0" - ], - "description": "Client library for Google APIs", - "homepage": "http://developers.google.com/api-client-library/php", - "keywords": [ - "google" - ], - "time": "2016-06-24T16:44:42+00:00" - }, - { - "name": "google/apiclient-services", - "version": "dev-master", - "source": { - "type": "git", - "url": "https://github.com/googleapis/google-api-php-client-services.git", - "reference": "d7a06d07832dbc6759d8f27ef29ccd6caed62735" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/d7a06d07832dbc6759d8f27ef29ccd6caed62735", - "reference": "d7a06d07832dbc6759d8f27ef29ccd6caed62735", - "shasum": "" - }, - "require": { - "php": ">=5.4" - }, - "require-dev": { - "phpunit/phpunit": "~4.8" - }, - "type": "library", - "autoload": { - "psr-0": { - "Google_Service_": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "Apache-2.0" - ], - "description": "Client library for Google APIs", - "homepage": "http://developers.google.com/api-client-library/php", - "keywords": [ - "google" - ], - "time": "2019-01-31T00:23:01+00:00" - }, - { - "name": "google/auth", - "version": "v0.9", - "source": { - "type": "git", - "url": "https://github.com/googleapis/google-auth-library-php.git", - "reference": "47c3c6bece495e58381a21fed13a735bd23a51cc" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/47c3c6bece495e58381a21fed13a735bd23a51cc", - "reference": "47c3c6bece495e58381a21fed13a735bd23a51cc", - "shasum": "" - }, - "require": { - "firebase/php-jwt": "~2.0|~3.0", - "guzzlehttp/guzzle": "~5.3|~6.0", - "guzzlehttp/psr7": "~1.2", - "php": ">=5.4", - "psr/cache": "^1.0", - "psr/http-message": "^1.0" - }, - "require-dev": { - "friendsofphp/php-cs-fixer": "^1.11", - "phpunit/phpunit": "3.7.*" - }, - "type": "library", - "autoload": { - "classmap": [ - "src/" - ], - "psr-4": { - "Google\\Auth\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "Apache-2.0" - ], - "description": "Google Auth Library for PHP", - "homepage": "http://github.com/google/google-auth-library-php", - "keywords": [ - "Authentication", - "google", - "oauth2" - ], - "time": "2016-06-01T22:07:52+00:00" - }, - { - "name": "guzzlehttp/guzzle", - "version": "6.3.3", - "source": { - "type": "git", - "url": "https://github.com/guzzle/guzzle.git", - "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle/zipball/407b0cb880ace85c9b63c5f9551db498cb2d50ba", - "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba", - "shasum": "" - }, - "require": { - "guzzlehttp/promises": "^1.0", - "guzzlehttp/psr7": "^1.4", - "php": ">=5.5" - }, - "require-dev": { - "ext-curl": "*", - "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0", - "psr/log": "^1.0" - }, - "suggest": { - "psr/log": "Required for using the Log middleware" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "6.3-dev" - } - }, - "autoload": { - "files": [ - "src/functions_include.php" - ], - "psr-4": { - "GuzzleHttp\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "description": "Guzzle is a PHP HTTP client library", - "homepage": "http://guzzlephp.org/", - "keywords": [ - "client", - "curl", - "framework", - "http", - "http client", - "rest", - "web service" - ], - "time": "2018-04-22T15:46:56+00:00" - }, - { - "name": "guzzlehttp/promises", - "version": "v1.3.1", - "source": { - "type": "git", - "url": "https://github.com/guzzle/promises.git", - "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", - "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", - "shasum": "" - }, - "require": { - "php": ">=5.5.0" - }, - "require-dev": { - "phpunit/phpunit": "^4.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.4-dev" - } - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\Promise\\": "src/" - }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "description": "Guzzle promises library", - "keywords": [ - "promise" - ], - "time": "2016-12-20T10:07:11+00:00" - }, - { - "name": "guzzlehttp/psr7", - "version": "1.5.2", - "source": { - "type": "git", - "url": "https://github.com/guzzle/psr7.git", - "reference": "9f83dded91781a01c63574e387eaa769be769115" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/9f83dded91781a01c63574e387eaa769be769115", - "reference": "9f83dded91781a01c63574e387eaa769be769115", - "shasum": "" - }, - "require": { - "php": ">=5.4.0", - "psr/http-message": "~1.0", - "ralouphie/getallheaders": "^2.0.5" - }, - "provide": { - "psr/http-message-implementation": "1.0" - }, - "require-dev": { - "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.5-dev" - } - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\Psr7\\": "src/" - }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - }, - { - "name": "Tobias Schultze", - "homepage": "https://github.com/Tobion" - } - ], - "description": "PSR-7 message implementation that also provides common utility methods", - "keywords": [ - "http", - "message", - "psr-7", - "request", - "response", - "stream", - "uri", - "url" - ], - "time": "2018-12-04T20:46:45+00:00" - }, - { - "name": "monolog/monolog", - "version": "1.24.0", - "source": { - "type": "git", - "url": "https://github.com/Seldaek/monolog.git", - "reference": "bfc9ebb28f97e7a24c45bdc3f0ff482e47bb0266" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/bfc9ebb28f97e7a24c45bdc3f0ff482e47bb0266", - "reference": "bfc9ebb28f97e7a24c45bdc3f0ff482e47bb0266", - "shasum": "" - }, - "require": { - "php": ">=5.3.0", - "psr/log": "~1.0" - }, - "provide": { - "psr/log-implementation": "1.0.0" - }, - "require-dev": { - "aws/aws-sdk-php": "^2.4.9 || ^3.0", - "doctrine/couchdb": "~1.0@dev", - "graylog2/gelf-php": "~1.0", - "jakub-onderka/php-parallel-lint": "0.9", - "php-amqplib/php-amqplib": "~2.4", - "php-console/php-console": "^3.1.3", - "phpunit/phpunit": "~4.5", - "phpunit/phpunit-mock-objects": "2.3.0", - "ruflin/elastica": ">=0.90 <3.0", - "sentry/sentry": "^0.13", - "swiftmailer/swiftmailer": "^5.3|^6.0" - }, - "suggest": { - "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", - "doctrine/couchdb": "Allow sending log messages to a CouchDB server", - "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", - "ext-mongo": "Allow sending log messages to a MongoDB server", - "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", - "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", - "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", - "php-console/php-console": "Allow sending log messages to Google Chrome", - "rollbar/rollbar": "Allow sending log messages to Rollbar", - "ruflin/elastica": "Allow sending log messages to an Elastic Search server", - "sentry/sentry": "Allow sending log messages to a Sentry server" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Monolog\\": "src/Monolog" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jordi Boggiano", - "email": "j.boggiano@seld.be", - "homepage": "http://seld.be" - } - ], - "description": "Sends your logs to files, sockets, inboxes, databases and various web services", - "homepage": "http://github.com/Seldaek/monolog", - "keywords": [ - "log", - "logging", - "psr-3" - ], - "time": "2018-11-05T09:00:11+00:00" - }, - { - "name": "phpseclib/phpseclib", - "version": "2.0.31", - "source": { - "type": "git", - "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "233a920cb38636a43b18d428f9a8db1f0a1a08f4" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/233a920cb38636a43b18d428f9a8db1f0a1a08f4", - "reference": "233a920cb38636a43b18d428f9a8db1f0a1a08f4", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "require-dev": { - "phing/phing": "~2.7", - "phpunit/phpunit": "^4.8.35|^5.7|^6.0|^9.4", - "squizlabs/php_codesniffer": "~2.0" - }, - "suggest": { - "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", - "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", - "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", - "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." - }, - "type": "library", - "autoload": { - "files": [ - "phpseclib/bootstrap.php" - ], - "psr-4": { - "phpseclib\\": "phpseclib/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jim Wigginton", - "email": "terrafrost@php.net", - "role": "Lead Developer" - }, - { - "name": "Patrick Monnerat", - "email": "pm@datasphere.ch", - "role": "Developer" - }, - { - "name": "Andreas Fischer", - "email": "bantu@phpbb.com", - "role": "Developer" - }, - { - "name": "Hans-Jürgen Petrich", - "email": "petrich@tronic-media.com", - "role": "Developer" - }, - { - "name": "Graham Campbell", - "email": "graham@alt-three.com", - "role": "Developer" - } - ], - "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", - "homepage": "http://phpseclib.sourceforge.net", - "keywords": [ - "BigInteger", - "aes", - "asn.1", - "asn1", - "blowfish", - "crypto", - "cryptography", - "encryption", - "rsa", - "security", - "sftp", - "signature", - "signing", - "ssh", - "twofish", - "x.509", - "x509" - ], - "support": { - "issues": "https://github.com/phpseclib/phpseclib/issues", - "source": "https://github.com/phpseclib/phpseclib/tree/2.0.31" - }, - "funding": [ - { - "url": "https://github.com/terrafrost", - "type": "github" - }, - { - "url": "https://www.patreon.com/phpseclib", - "type": "patreon" - }, - { - "url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib", - "type": "tidelift" - } - ], - "time": "2021-04-06T13:56:45+00:00" - }, - { - "name": "psr/cache", - "version": "1.0.1", - "source": { - "type": "git", - "url": "https://github.com/php-fig/cache.git", - "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8", - "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Cache\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for caching libraries", - "keywords": [ - "cache", - "psr", - "psr-6" - ], - "time": "2016-08-06T20:24:11+00:00" - }, - { - "name": "psr/http-message", - "version": "1.0.1", - "source": { - "type": "git", - "url": "https://github.com/php-fig/http-message.git", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Http\\Message\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for HTTP messages", - "homepage": "https://github.com/php-fig/http-message", - "keywords": [ - "http", - "http-message", - "psr", - "psr-7", - "request", - "response" - ], - "time": "2016-08-06T14:39:51+00:00" - }, - { - "name": "psr/log", - "version": "1.1.0", - "source": { - "type": "git", - "url": "https://github.com/php-fig/log.git", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Log\\": "Psr/Log/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for logging libraries", - "homepage": "https://github.com/php-fig/log", - "keywords": [ - "log", - "psr", - "psr-3" - ], - "time": "2018-11-20T15:27:04+00:00" - }, - { - "name": "ralouphie/getallheaders", - "version": "2.0.5", - "source": { - "type": "git", - "url": "https://github.com/ralouphie/getallheaders.git", - "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/5601c8a83fbba7ef674a7369456d12f1e0d0eafa", - "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa", - "shasum": "" - }, - "require": { - "php": ">=5.3" - }, - "require-dev": { - "phpunit/phpunit": "~3.7.0", - "satooshi/php-coveralls": ">=1.0" - }, - "type": "library", - "autoload": { - "files": [ - "src/getallheaders.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Ralph Khattar", - "email": "ralph.khattar@gmail.com" - } - ], - "description": "A polyfill for getallheaders.", - "time": "2016-02-11T07:05:27+00:00" - } - ], - "packages-dev": [], - "aliases": [], - "minimum-stability": "stable", - "stability-flags": { - "google/apiclient-services": 20 - }, - "prefer-stable": false, - "prefer-lowest": false, - "platform": [], - "platform-dev": [] -} diff --git a/php/v3.4/examples/Ads/CreateRotationGroup.php b/php/v3.4/examples/Ads/CreateRotationGroup.php deleted file mode 100755 index 7c44556..0000000 --- a/php/v3.4/examples/Ads/CreateRotationGroup.php +++ /dev/null @@ -1,140 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'creative_id', - 'display' => 'Creative ID', - 'required' => true], - ['name' => 'placement_id', - 'display' => 'Placement ID', - 'required' => true], - ['name' => 'ad_name', - 'display' => 'Ad Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating rotation group ad with name "%s" for placement ID' - . ' %s

', - $values['ad_name'], - $values['placement_id'] - ); - - // Retrieve the campaign. - $campaign = $this->service->campaigns->get( - $values['user_profile_id'], - $values['campaign_id'] - ); - - // Create a click-through URL. - $url = new Google_Service_Dfareporting_ClickThroughUrl(); - $url->setDefaultLandingPage(true); - - // Create a creative assignment. - $creativeAssignment = - new Google_Service_Dfareporting_CreativeAssignment(); - $creativeAssignment->setActive(true); - $creativeAssignment->setCreativeId($values['creative_id']); - $creativeAssignment->setClickThroughUrl($url); - - // Create a placement assignment. - $placementAssignment = - new Google_Service_Dfareporting_PlacementAssignment(); - $placementAssignment->setActive(true); - $placementAssignment->setPlacementId($values['placement_id']); - - // Create a creative rotation. - $creativeRotation = new Google_Service_Dfareporting_CreativeRotation(); - $creativeRotation->setCreativeAssignments([$creativeAssignment]); - - // Create a delivery schedule. - $deliverySchedule = new Google_Service_Dfareporting_DeliverySchedule(); - $deliverySchedule->setImpressionRatio(1); - $deliverySchedule->SetPriority('AD_PRIORITY_01'); - - $startDate = new DateTime('today'); - $endDate = new DateTime($campaign->getEndDate()); - - // Create a rotation group. - $ad = new Google_Service_Dfareporting_Ad(); - $ad->setActive(true); - $ad->setCampaignId($values['campaign_id']); - $ad->setCreativeRotation($creativeRotation); - $ad->setDeliverySchedule($deliverySchedule); - $ad->setStartTime($startDate->format('Y-m-d') . 'T23:59:59Z'); - $ad->setEndTime($endDate->format('Y-m-d') . 'T00:00:00Z'); - $ad->setName($values['ad_name']); - $ad->setPlacementAssignments([$placementAssignment]); - $ad->setType('AD_SERVING_STANDARD_AD'); - - $result = $this->service->ads->insert($values['user_profile_id'], $ad); - - $this->printResultsTable('Rotation group ad created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Rotation Group Ad'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Ad ID', - 'name' => 'Ad Name']; - } -} diff --git a/php/v3.4/examples/Ads/GetAds.php b/php/v3.4/examples/Ads/GetAds.php deleted file mode 100755 index e62e6e3..0000000 --- a/php/v3.4/examples/Ads/GetAds.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all ads

'; - - $this->printResultsTableHeader('Ads'); - - $response = null; - $pageToken = null; - - do { - // Create and execute the ads list request. - $response = $this->service->ads->listAds( - $values['user_profile_id'], - ['active' => true, 'pageToken' => $pageToken] - ); - - foreach ($response->getAds() as $ads) { - $this->printResultsTableRow($ads); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getAds()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Ads'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Ad ID', - 'name' => 'Ad Name', - 'advertiserId' => 'Associated Advertiser ID']; - } -} diff --git a/php/v3.4/examples/Advertisers/AssignAdvertisersToAdvertiserGroup.php b/php/v3.4/examples/Advertisers/AssignAdvertisersToAdvertiserGroup.php deleted file mode 100755 index b78c16b..0000000 --- a/php/v3.4/examples/Advertisers/AssignAdvertisersToAdvertiserGroup.php +++ /dev/null @@ -1,94 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'advertiser_group_id', - 'display' => 'Advertiser Group ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Assigning advertiser ID %s to advertiser group ID %s

', - $values['advertiser_id'], - $values['advertiser_group_id'] - ); - - $advertiser = new Google_Service_Dfareporting_Advertiser(); - $advertiser->setAdvertiserGroupId($values['advertiser_group_id']); - - $result = $this->service->advertisers->patch( - $values['user_profile_id'], - $values['advertiser_id'], - $advertiser - ); - - $this->printResultsTable('Advertiser', [$result]); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Assign Advertiser To Advertiser Group'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser ID', - 'name' => 'Advertiser Name', - 'advertiserGroupId' => 'Advertiser Group ID']; - } -} diff --git a/php/v3.4/examples/Advertisers/CreateAdvertiser.php b/php/v3.4/examples/Advertisers/CreateAdvertiser.php deleted file mode 100755 index f41447f..0000000 --- a/php/v3.4/examples/Advertisers/CreateAdvertiser.php +++ /dev/null @@ -1,87 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_name', - 'display' => 'Advertiser Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating advertiser with name "%s"

', - $values['advertiser_name'] - ); - - $advertiser = new Google_Service_Dfareporting_Advertiser(); - $advertiser->setName($values['advertiser_name']); - $advertiser->setStatus('APPROVED'); - - $result = $this->service->advertisers->insert( - $values['user_profile_id'], - $advertiser - ); - - $this->printResultsTable('Advertiser created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Advertiser'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser ID', - 'name' => 'Advertiser Name']; - } -} diff --git a/php/v3.4/examples/Advertisers/CreateAdvertiserGroup.php b/php/v3.4/examples/Advertisers/CreateAdvertiserGroup.php deleted file mode 100755 index c984cae..0000000 --- a/php/v3.4/examples/Advertisers/CreateAdvertiserGroup.php +++ /dev/null @@ -1,87 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_group_name', - 'display' => 'Advertiser Group Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating advertiser group with name "%s"

', - $values['advertiser_group_name'] - ); - - $advertiser = new Google_Service_Dfareporting_AdvertiserGroup(); - $advertiser->setName($values['advertiser_group_name']); - - - $result = $this->service->advertiserGroups->insert( - $values['user_profile_id'], - $advertiser - ); - - $this->printResultsTable('Advertiser group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Advertiser Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Group ID', - 'name' => 'Advertiser Group Name']; - } -} diff --git a/php/v3.4/examples/Advertisers/CreateAdvertiserLandingPage.php b/php/v3.4/examples/Advertisers/CreateAdvertiserLandingPage.php deleted file mode 100755 index bef2442..0000000 --- a/php/v3.4/examples/Advertisers/CreateAdvertiserLandingPage.php +++ /dev/null @@ -1,95 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'landing_page_name', - 'display' => 'Landing Page Name', - 'required' => true], - ['name' => 'landing_page_url', - 'display' => 'Landing Page URL', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating advertiser landing page for advertiser %d

', - $values['advertiser_id'] - ); - - $landingPage = new Google_Service_Dfareporting_LandingPage(); - $landingPage->setAdvertiserId($values['advertiser_id']); - $landingPage->setArchived(false); - $landingPage->setName($values['landing_page_name']); - $landingPage->setUrl($values['landing_page_url']); - - $result = $this->service->advertiserLandingPages->insert( - $values['user_profile_id'], - $landingPage - ); - - $this->printResultsTable('Advertiser landing page created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Advertiser Landing Page'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Landing Page ID', - 'name' => 'Advertiser Landing Page Name', - 'url' => 'Advertiser Landing Page URL']; - } -} diff --git a/php/v3.4/examples/Advertisers/GetAdvertiserGroups.php b/php/v3.4/examples/Advertisers/GetAdvertiserGroups.php deleted file mode 100755 index 714c04c..0000000 --- a/php/v3.4/examples/Advertisers/GetAdvertiserGroups.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all advertiser groups

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Advertiser groups'); - - do { - // Create and execute the advertiser groups list request. - $response = $this->service->advertiserGroups->listAdvertiserGroups( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getAdvertiserGroups() as $group) { - $this->printResultsTableRow($group); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getAdvertiserGroups()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Advertiser Groups'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Group ID', - 'name' => 'Advertiser Group Name']; - } -} diff --git a/php/v3.4/examples/Advertisers/GetAdvertiserLandingPages.php b/php/v3.4/examples/Advertisers/GetAdvertiserLandingPages.php deleted file mode 100755 index f986b58..0000000 --- a/php/v3.4/examples/Advertisers/GetAdvertiserLandingPages.php +++ /dev/null @@ -1,101 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all landing pages for advertiser %d

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Advertiser landing pages'); - - do { - // Create and execute the advertiser landing page list request. - $response = - $this->service->advertiserLandingPages->listAdvertiserLandingPages( - $values['user_profile_id'], - ['advertiserIds' => [$values['advertiser_id']], - 'pageToken' => $pageToken] - ); - - foreach ($response->getLandingPages() as $landingPage) { - $this->printResultsTableRow($landingPage); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getLandingPages()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Advertiser Landing Pages'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Landing Page ID', - 'name' => 'Advertiser Landing Page Name', - 'url' => 'Advertiser Landing Page URL']; - } -} diff --git a/php/v3.4/examples/Advertisers/GetAdvertisers.php b/php/v3.4/examples/Advertisers/GetAdvertisers.php deleted file mode 100755 index 0a31931..0000000 --- a/php/v3.4/examples/Advertisers/GetAdvertisers.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all advertisers

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Advertisers'); - - do { - // Create and execute the advertisers list request. - $response = $this->service->advertisers->listAdvertisers( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getAdvertisers() as $advertiser) { - $this->printResultsTableRow($advertiser); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getAdvertisers()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Advertisers'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser ID', - 'name' => 'Advertiser Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.4/examples/BaseExample.php b/php/v3.4/examples/BaseExample.php deleted file mode 100755 index 94daa42..0000000 --- a/php/v3.4/examples/BaseExample.php +++ /dev/null @@ -1,277 +0,0 @@ -service = $service; - $this->headers = $this->getResultsTableHeaders(); - } - - /** - * Contains the logic of the example. - */ - abstract protected function run(); - - /** - * Executes the example, checks if the examples requires parameters and - * request them before invoking run. - */ - public function execute() - { - if (count($this->getInputParameters())) { - if ($this->isSubmitComplete()) { - $this->formValues = $this->getFormValues(); - $this->run(); - } else { - $this->renderInputForm(); - } - } else { - $this->run(); - } - } - - /** - * Returns a display name for the example. - * @return string - */ - abstract public function getName(); - - /** - * Returns the list of input parameters of the example. - * To be overridden by examples that require parameters. - * @return array - */ - protected function getInputParameters() - { - return []; - } - - /** - * Returns the list of headers to be shown in the results table. - * To be overridden by examples that require table headers. - * @return array - */ - protected function getResultsTableHeaders() - { - return []; - } - - /** - * Renders an input form to capture the example parameters. - */ - protected function renderInputForm() - { - $parameters = $this->getInputParameters(); - if (count($parameters)) { - printf('

Enter %s parameters

', $this->getName()); - print '
'; - foreach ($parameters as $parameter) { - $name = $parameter['name']; - $display = $parameter['display']; - - if (isset($_POST[$name])) { - $currentValue = $_POST[$name]; - } else { - $currentValue = ''; - } - - // If this is a file parameter, generate a file input element - if ($parameter['file']) { - $inputType = ' type="file"'; - } - - printf( - '%s: ', - $display, - $name, - $currentValue, - $inputType - ); - - if ($parameter['required']) { - print '*'; - } - - print '
'; - } - print '
*required
'; - print ''; - print '
'; - } - - $this->flush(); - } - - /** - * Checks if the form has been submitted and all required parameters are - * set. - * @return bool - */ - protected function isSubmitComplete() - { - if (!isset($_POST['submit'])) { - return false; - } - - foreach ($this->getInputParameters() as $parameter) { - if ($parameter['required']) { - if ($parameter['file']) { - return !empty($_FILES[$parameter['name']]); - } else { - return !empty($_POST[$parameter['name']]); - } - } - } - - return true; - } - - /** - * Retrieves the submitted form values. - * @return array - */ - protected function getFormValues() - { - $input = []; - - foreach ($this->getInputParameters() as $parameter) { - if ($parameter['file'] && isset($_FILES[$parameter['name']])) { - $input[$parameter['name']] = $_FILES[$parameter['name']]; - } elseif (isset($_POST[$parameter['name']])) { - $input[$parameter['name']] = $_POST[$parameter['name']]; - } - } - - return $input; - } - - /** - * Prints out the header for the results table. - * @param string $title - * A friendly name for the results table - */ - protected function printResultsTableHeader($title) - { - printf('

%s

', $title); - print ''; - - foreach ($this->headers as $name => $value) { - printf('', $value); - } - - print ''; - $this->flush(); - } - - /** - * Prints out a row of data for the results table. - * @param array $row - * Values representing a single row in the results table - */ - protected function printResultsTableRow($row) - { - print ''; - - foreach ($this->headers as $name => $value) { - print ''; - } - - print ''; - $this->flush(); - } - - /** - * Prints out a "No results" row for the results table. - */ - protected function printNoResultsTableRow() - { - print ''; - printf( - '', - count($this->headers) - ); - print ''; - $this->flush(); - } - - /** - * Prints out the footer for the results table. - */ - protected function printResultsTableFooter() - { - print '
%s
'; - print_r($row[$name]); - print '
No results.

'; - $this->flush(); - } - - /** - * Convenience method to print an entire results table at once. - * @param string $title - * A friendly name for the results table - * @param array $rows - * Values representing multiple rows in the results table - */ - protected function printResultsTable($title, $rows) - { - $this->printResultsTableHeader($title); - - if (empty($rows)) { - $this->printNoResultsTableRow(); - } else { - foreach ($rows as $row) { - $this->printResultsTableRow($row); - } - } - - $this->printResultsTableFooter(); - } - - /** - * Flushes the contents of the output buffer. - */ - protected function flush() - { - ob_flush(); - flush(); - } -} diff --git a/php/v3.4/examples/Campaigns/CreateCampaign.php b/php/v3.4/examples/Campaigns/CreateCampaign.php deleted file mode 100755 index 5fa4c7e..0000000 --- a/php/v3.4/examples/Campaigns/CreateCampaign.php +++ /dev/null @@ -1,99 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'campaign_name', - 'display' => 'Campaign Name', - 'required' => true], - ['name' => 'default_landing_page_id', - 'display' => 'Default Landing Page ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating campaign with name "%s"

', - $values['campaign_name'] - ); - - $startDate = new DateTime('today'); - $endDate = new DateTime('+1 month'); - - $campaign = new Google_Service_Dfareporting_Campaign(); - $campaign->setAdvertiserId($values['advertiser_id']); - $campaign->setDefaultLandingPageId($values['default_landing_page_id']); - $campaign->setName($values['campaign_name']); - $campaign->setStartDate($startDate->format('Y-m-d')); - $campaign->setEndDate($endDate->format('Y-m-d')); - - $result = $this->service->campaigns->insert( - $values['user_profile_id'], - $campaign - ); - - $this->printResultsTable('Campaign created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Campaign'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Campaign ID', - 'name' => 'Campaign Name']; - } -} diff --git a/php/v3.4/examples/Campaigns/CreateCampaignEventTag.php b/php/v3.4/examples/Campaigns/CreateCampaignEventTag.php deleted file mode 100755 index ebf57a3..0000000 --- a/php/v3.4/examples/Campaigns/CreateCampaignEventTag.php +++ /dev/null @@ -1,95 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'event_tag_name', - 'display' => 'Event Tag Name', - 'required' => true], - ['name' => 'event_tag_url', - 'display' => 'Event Tag URL', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating campaign event tag with name "%s"

', - $values['event_tag_name'] - ); - - $eventTag = new Google_Service_Dfareporting_EventTag(); - $eventTag->setCampaignId($values['campaign_id']); - $eventTag->setName($values['event_tag_name']); - $eventTag->setStatus('ENABLED'); - $eventTag->setType('CLICK_THROUGH_EVENT_TAG'); - $eventTag->setUrl($values['event_tag_url']); - - $result = $this->service->eventTags->insert( - $values['user_profile_id'], - $eventTag - ); - - $this->printResultsTable('Campaign event tag created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Campaign Event Tag'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Event Tag ID', - 'name' => 'Event Tag Name']; - } -} diff --git a/php/v3.4/examples/Campaigns/GetCampaigns.php b/php/v3.4/examples/Campaigns/GetCampaigns.php deleted file mode 100755 index 12ff8b9..0000000 --- a/php/v3.4/examples/Campaigns/GetCampaigns.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all campaigns

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Campaigns'); - - do { - // Create and execute the ads list request. - $response = $this->service->campaigns->listCampaigns( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCampaigns() as $campaigns) { - $this->printResultsTableRow($campaigns); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCampaigns()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Campaigns'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Campaign ID', - 'name' => 'Campaign Name']; - } -} diff --git a/php/v3.4/examples/Conversions/InsertOfflineMobileConversion.php b/php/v3.4/examples/Conversions/InsertOfflineMobileConversion.php deleted file mode 100755 index a75882c..0000000 --- a/php/v3.4/examples/Conversions/InsertOfflineMobileConversion.php +++ /dev/null @@ -1,110 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'mobile_device_id', - 'display' => 'Mobile Device ID', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Inserting offline conversion for mobile device ID "%s"

', - $values['mobile_device_id'] - ); - - $currentTimeInMicros = time() * 1000 * 1000; - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setMobileDeviceId($values['mobile_device_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($currentTimeInMicros); - $conversion->setTimestampMicros($currentTimeInMicros); - - $batch = new Google_Service_Dfareporting_ConversionsBatchInsertRequest(); - $batch->setConversions([$conversion]); - - $result = $this->service->conversions->batchinsert( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully inserted conversion for mobile device ID %s.', - $values['mobile_device_id'] - ); - } else { - printf( - 'Error(s) inserting conversion for mobile device ID %s:

', - $values['mobile_device_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Insert Offline Mobile Conversion'; - } -} diff --git a/php/v3.4/examples/Conversions/InsertOfflineUserConversion.php b/php/v3.4/examples/Conversions/InsertOfflineUserConversion.php deleted file mode 100755 index 7893824..0000000 --- a/php/v3.4/examples/Conversions/InsertOfflineUserConversion.php +++ /dev/null @@ -1,125 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'encrypted_user_id', - 'display' => 'Encrypted User ID', - 'required' => true], - ['name' => 'encryption_entity_id', - 'display' => 'Encryption Entity ID', - 'required' => true], - ['name' => 'encryption_entity_type', - 'display' => 'Encryption Entity Type', - 'required' => true], - ['name' => 'encryption_source', - 'display' => 'Encryption Source', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Inserting offline conversion for encrypted user ID "%s"

', - $values['encrypted_user_id'] - ); - - $currentTimeInMicros = time() * 1000 * 1000; - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setEncryptedUserId($values['encrypted_user_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($currentTimeInMicros); - $conversion->setTimestampMicros($currentTimeInMicros); - - $encryptionInfo = new Google_Service_Dfareporting_EncryptionInfo(); - $encryptionInfo->setEncryptionEntityId($values['encryption_entity_id']); - $encryptionInfo->setEncryptionEntityType($values['encryption_entity_type']); - $encryptionInfo->setEncryptionSource($values['encryption_source']); - - $batch = new Google_Service_Dfareporting_ConversionsBatchInsertRequest(); - $batch->setConversions([$conversion]); - $batch->setEncryptionInfo($encryptionInfo); - - $result = $this->service->conversions->batchinsert( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully inserted conversion for encrypted user ID %s.', - $values['encrypted_user_id'] - ); - } else { - printf( - 'Error(s) inserting conversion for encrypted user ID %s:

', - $values['encrypted_user_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Insert Offline User Conversion'; - } -} diff --git a/php/v3.4/examples/Conversions/UpdateOfflineMobileConversion.php b/php/v3.4/examples/Conversions/UpdateOfflineMobileConversion.php deleted file mode 100755 index 587de8d..0000000 --- a/php/v3.4/examples/Conversions/UpdateOfflineMobileConversion.php +++ /dev/null @@ -1,127 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'mobile_device_id', - 'display' => 'Mobile Device ID', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true], - ['name' => 'ordinal', - 'display' => 'Ordinal', - 'required' => true], - ['name' => 'timestamp', - 'display' => 'Timestamp (microseconds)', - 'required' => true], - ['name' => 'new_quantity', - 'display' => 'New Quantity', - 'required' => true], - ['name' => 'new_value', - 'display' => 'New Value', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Updating offline conversion for mobile device ID "%s"

', - $values['mobile_device_id'] - ); - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - // Create a conversion object with values that identify the conversion to - // update. - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setMobileDeviceId($values['mobile_device_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($values['ordinal']); - $conversion->setTimestampMicros($values['timestamp']); - - // Set the fields to be updated. These fields are required; to preserve a - // value from the existing conversion, it must be copied over manually. - $conversion->setQuantity($values['new_quantity']); - $conversion->setValue($values['new_value']); - - $batch = new Google_Service_Dfareporting_ConversionsBatchUpdateRequest(); - $batch->setConversions([$conversion]); - - $result = $this->service->conversions->batchupdate( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully updated conversion for mobile device ID %s.', - $values['mobile_device_id'] - ); - } else { - printf( - 'Error(s) updating conversion for mobile device ID %s:

', - $values['mobile_device_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Update Offline Mobile Conversion'; - } -} diff --git a/php/v3.4/examples/Conversions/UpdateOfflineUserConversion.php b/php/v3.4/examples/Conversions/UpdateOfflineUserConversion.php deleted file mode 100755 index aa09117..0000000 --- a/php/v3.4/examples/Conversions/UpdateOfflineUserConversion.php +++ /dev/null @@ -1,142 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'encrypted_user_id', - 'display' => 'Encrypted User ID', - 'required' => true], - ['name' => 'encryption_entity_id', - 'display' => 'Encryption Entity ID', - 'required' => true], - ['name' => 'encryption_entity_type', - 'display' => 'Encryption Entity Type', - 'required' => true], - ['name' => 'encryption_source', - 'display' => 'Encryption Source', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true], - ['name' => 'ordinal', - 'display' => 'Ordinal', - 'required' => true], - ['name' => 'timestamp', - 'display' => 'Timestamp (microseconds)', - 'required' => true], - ['name' => 'new_quantity', - 'display' => 'New Quantity', - 'required' => true], - ['name' => 'new_value', - 'display' => 'New Value', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Updating offline conversion for encrypted user ID "%s"

', - $values['encrypted_user_id'] - ); - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - // Create a conversion object with values that identify the conversion to - // update. - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setEncryptedUserId($values['encrypted_user_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($values['ordinal']); - $conversion->setTimestampMicros($values['timestamp']); - - // Set the fields to be updated. These fields are required; to preserve a - // value from the existing conversion, it must be copied over manually. - $conversion->setQuantity($values['new_quantity']); - $conversion->setValue($values['new_value']); - - $encryptionInfo = new Google_Service_Dfareporting_EncryptionInfo(); - $encryptionInfo->setEncryptionEntityId($values['encryption_entity_id']); - $encryptionInfo->setEncryptionEntityType($values['encryption_entity_type']); - $encryptionInfo->setEncryptionSource($values['encryption_source']); - - $batch = new Google_Service_Dfareporting_ConversionsBatchUpdateRequest(); - $batch->setConversions([$conversion]); - $batch->setEncryptionInfo($encryptionInfo); - - $result = $this->service->conversions->batchupdate( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully updated conversion for encrypted user ID %s.', - $values['encrypted_user_id'] - ); - } else { - printf( - 'Error(s) updating conversion for encrypted user ID %s:

', - $values['encrypted_user_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Update Offline User Conversion'; - } -} diff --git a/php/v3.4/examples/CreativeAssetUtils.php b/php/v3.4/examples/CreativeAssetUtils.php deleted file mode 100755 index 4ee64bb..0000000 --- a/php/v3.4/examples/CreativeAssetUtils.php +++ /dev/null @@ -1,42 +0,0 @@ -setName($asset['name']); - $assetId->setType($type); - - $metadata = new Google_Service_Dfareporting_CreativeAssetMetadata(); - $metadata->setAssetIdentifier($assetId); - - $result = $service->creativeAssets->insert( - $userProfileId, - $advertiserId, - $metadata, - ['data' => file_get_contents($asset['tmp_name']), - 'mimeType' => $asset['type'], - 'uploadType' => 'multipart'] - ); - - return $result; -} diff --git a/php/v3.4/examples/Creatives/AssignCreativeToCampaign.php b/php/v3.4/examples/Creatives/AssignCreativeToCampaign.php deleted file mode 100755 index 320014a..0000000 --- a/php/v3.4/examples/Creatives/AssignCreativeToCampaign.php +++ /dev/null @@ -1,85 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'creative_id', - 'display' => 'Creative ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Assigning creative ID %s to campaign ID %s

', - $values['creative_id'], - $values['campaign_id'] - ); - - $association = - new Google_Service_Dfareporting_CampaignCreativeAssociation(); - $association->setCreativeId($values['creative_id']); - - $result = $this->service->campaignCreativeAssociations->insert( - $values['user_profile_id'], - $values['campaign_id'], - $association - ); - - printf( - 'Successfully associated creative ID %s with campaign ID %s.', - $result->getCreativeId(), - $values['campaign_id'] - ); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Assign Creative To Campaign'; - } -} diff --git a/php/v3.4/examples/Creatives/CreateCreativeField.php b/php/v3.4/examples/Creatives/CreateCreativeField.php deleted file mode 100755 index 58b222b..0000000 --- a/php/v3.4/examples/Creatives/CreateCreativeField.php +++ /dev/null @@ -1,90 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'field_name', - 'display' => 'Creative Field Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating creative field with name "%s"

', - $values['field_name'] - ); - - $field = new Google_Service_Dfareporting_CreativeField(); - $field->setAdvertiserId($values['advertiser_id']); - $field->setName($values['field_name']); - - $result = $this->service->creativeFields->insert( - $values['user_profile_id'], - $field - ); - - $this->printResultsTable('Creative field created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Creative Field'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field ID', - 'name' => 'Creative Field Name']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateCreativeFieldValue.php b/php/v3.4/examples/Creatives/CreateCreativeFieldValue.php deleted file mode 100755 index e454eb0..0000000 --- a/php/v3.4/examples/Creatives/CreateCreativeFieldValue.php +++ /dev/null @@ -1,90 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'creative_field_id', - 'display' => 'Creative Field ID', - 'required' => true], - ['name' => 'field_value', - 'display' => 'Creative Field Value', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating creative field value with value "%s"

', - $values['field_value'] - ); - - $fieldValue = new Google_Service_Dfareporting_CreativeFieldValue(); - $fieldValue->setValue($values['field_value']); - - $result = $this->service->creativeFieldValues->insert( - $values['user_profile_id'], - $values['creative_field_id'], - $fieldValue - ); - - $this->printResultsTable('Creative field value created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Creative Field Value'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field Value ID', - 'value' => 'Creative Field Value']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateCreativeGroup.php b/php/v3.4/examples/Creatives/CreateCreativeGroup.php deleted file mode 100755 index 74a41a4..0000000 --- a/php/v3.4/examples/Creatives/CreateCreativeGroup.php +++ /dev/null @@ -1,96 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'group_name', - 'display' => 'Creative Group Name', - 'required' => true], - ['name' => 'group_number', - 'display' => 'Creative Group Number (1-2)', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating creative group with name "%s"

', - $values['group_name'] - ); - - $group = new Google_Service_Dfareporting_CreativeGroup(); - $group->setAdvertiserId($values['advertiser_id']); - $group->setGroupNumber($values['group_number']); - $group->setName($values['group_name']); - - $result = $this->service->creativeGroups->insert( - $values['user_profile_id'], - $group - ); - - $this->printResultsTable('Creative group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Creative Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Group ID', - 'name' => 'Creative Group Name', - 'groupNumber' => 'Creative Group Number']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateDisplayImageGalleryCreative.php b/php/v3.4/examples/Creatives/CreateDisplayImageGalleryCreative.php deleted file mode 100755 index 9f76041..0000000 --- a/php/v3.4/examples/Creatives/CreateDisplayImageGalleryCreative.php +++ /dev/null @@ -1,151 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'image1_asset_file', - 'display' => 'First Image Asset File', - 'file' => true, - 'required' => true], - ['name' => 'image2_asset_file', - 'display' => 'Second Image Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating display image gallery creative from "%s" and "%s"

', - $values['image1_asset_file']['name'], - $values['image2_asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setAutoAdvanceImages(true); - $creative->setName('Test display image gallery creative'); - $creative->setType('DISPLAY_IMAGE_GALLERY'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the first image asset. - $image1 = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['image1_asset_file'], - 'HTML_IMAGE' - ); - - $image1Asset = new Google_Service_Dfareporting_CreativeAsset(); - $image1Asset->setAssetIdentifier($image1->getAssetIdentifier()); - $image1Asset->setRole('PRIMARY'); - - // Upload the second image asset. - $image2 = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['image2_asset_file'], - 'HTML_IMAGE' - ); - - $image2Asset = new Google_Service_Dfareporting_CreativeAsset(); - $image2Asset->setAssetIdentifier($image2->getAssetIdentifier()); - $image2Asset->setRole('PRIMARY'); - - // Add the creative assets. - $creative->setCreativeAssets([$image1Asset, $image2Asset]); - - // Add a click tag for the first image asset. - $clickTag1 = new Google_Service_Dfareporting_ClickTag(); - $clickTag1->setName($image1->getAssetIdentifier()->getName()); - $clickTag1->setEventName($image1->getAssetIdentifier()->getName()); - - // Add a click tag for the second image asset. - $clickTag2 = new Google_Service_Dfareporting_ClickTag(); - $clickTag2->setName($image2->getAssetIdentifier()->getName()); - $clickTag2->setEventName($image2->getAssetIdentifier()->getName()); - - $creative->setClickTags([$clickTag1, $clickTag2]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable( - 'Display image gallery creative created.', - [$result] - ); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Display Image Gallery Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateDisplayRedirectCreative.php b/php/v3.4/examples/Creatives/CreateDisplayRedirectCreative.php deleted file mode 100755 index 8e43514..0000000 --- a/php/v3.4/examples/Creatives/CreateDisplayRedirectCreative.php +++ /dev/null @@ -1,100 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'image_url', - 'display' => 'Image File URL', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating display redirect creative from image URL "%s"

', - $values['image_url'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test display redirect creative'); - $creative->setRedirectUrl($values['image_url']); - $creative->setType('DISPLAY_REDIRECT'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('Display redirect creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Display Redirect Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateHTML5DisplayCreative.php b/php/v3.4/examples/Creatives/CreateHTML5DisplayCreative.php deleted file mode 100755 index 566c761..0000000 --- a/php/v3.4/examples/Creatives/CreateHTML5DisplayCreative.php +++ /dev/null @@ -1,158 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'landing_page_id', - 'display' => 'Landing Page ID', - 'required' => true], - ['name' => 'html_asset_file', - 'display' => 'HTML5 Asset File', - 'file' => true, - 'required' => true], - ['name' => 'image_asset_file', - 'display' => 'Backup Image Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating HTML5 display creative from HTML5 asset "%s"

', - $values['html_asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setAutoAdvanceImages(true); - $creative->setName('Test HTML5 display creative'); - $creative->setType('DISPLAY'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the HTML5 asset. - $html = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['html_asset_file'], - 'HTML' - ); - - $htmlAsset = new Google_Service_Dfareporting_CreativeAsset(); - $htmlAsset->setAssetIdentifier($html->getAssetIdentifier()); - $htmlAsset->setRole('PRIMARY'); - - // Upload the backup image asset. - $image = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['image_asset_file'], - 'HTML_IMAGE' - ); - - $imageAsset = new Google_Service_Dfareporting_CreativeAsset(); - $imageAsset->setAssetIdentifier($image->getAssetIdentifier()); - $imageAsset->setRole('BACKUP_IMAGE'); - - // Add the creative assets. - $creative->setCreativeAssets([$htmlAsset, $imageAsset]); - - // Configure the default click-through URL. - $clickThroughUrl = - new Google_Service_Dfareporting_CreativeClickThroughUrl(); - $clickThroughUrl->setLandingPageId($values['landing_page_id']); - - // Configure the backup image. - $creative->setBackupImageClickThroughUrl($clickThroughUrl); - $creative->setBackupImageReportingLabel('backup'); - - $targetWindow = new Google_Service_Dfareporting_TargetWindow(); - $targetWindow->setTargetWindowOption('NEW_WINDOW'); - $creative->setBackupImageTargetWindow($targetWindow); - - // Add a click tag. - $clickTag = new Google_Service_Dfareporting_ClickTag(); - $clickTag->setName('clickTag'); - $clickTag->setEventName('exit'); - $clickTag->setClickThroughUrl($clickThroughUrl); - $creative->setClickTags([$clickTag]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('HTML5 display creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create HTML5 Display Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateImageDisplayCreative.php b/php/v3.4/examples/Creatives/CreateImageDisplayCreative.php deleted file mode 100755 index 9a2bac7..0000000 --- a/php/v3.4/examples/Creatives/CreateImageDisplayCreative.php +++ /dev/null @@ -1,117 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Image Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating image display creative from image asset "%s"

', - $values['asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test image display creative'); - $creative->setType('DISPLAY'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the image asset. - $image = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['asset_file'], - 'HTML_IMAGE' - ); - - $asset = new Google_Service_Dfareporting_CreativeAsset(); - $asset->setAssetIdentifier($image->getAssetIdentifier()); - $asset->setRole('PRIMARY'); - - // Add the creative asset. - $creative->setCreativeAssets([$asset]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('Image display creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Image Display Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateInstreamAudioCreative.php b/php/v3.4/examples/Creatives/CreateInstreamAudioCreative.php deleted file mode 100755 index e4545df..0000000 --- a/php/v3.4/examples/Creatives/CreateInstreamAudioCreative.php +++ /dev/null @@ -1,114 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Audio Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating in-stream audio creative from audio asset "%s"

', - $values['asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test in-stream audio creative'); - $creative->setType('INSTREAM_AUDIO'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the audio asset. - $audio = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['asset_file'], - 'AUDIO' - ); - - $asset = new Google_Service_Dfareporting_CreativeAsset(); - $asset->setAssetIdentifier($audio->getAssetIdentifier()); - $asset->setRole('PARENT_AUDIO'); - - // Add the creative asset. - $creative->setCreativeAssets([$asset]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('In-stream audio creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create In-stream Audio Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateInstreamVideoCreative.php b/php/v3.4/examples/Creatives/CreateInstreamVideoCreative.php deleted file mode 100755 index 3e27179..0000000 --- a/php/v3.4/examples/Creatives/CreateInstreamVideoCreative.php +++ /dev/null @@ -1,114 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Video Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating in-stream video creative from video asset "%s"

', - $values['asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test in-stream video creative'); - $creative->setType('INSTREAM_VIDEO'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the video asset. - $video = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['asset_file'], - 'VIDEO' - ); - - $asset = new Google_Service_Dfareporting_CreativeAsset(); - $asset->setAssetIdentifier($video->getAssetIdentifier()); - $asset->setRole('PARENT_VIDEO'); - - // Add the creative asset. - $creative->setCreativeAssets([$asset]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('In-stream video creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create In-stream Video Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.4/examples/Creatives/CreateTrackingCreative.php b/php/v3.4/examples/Creatives/CreateTrackingCreative.php deleted file mode 100755 index 63255a9..0000000 --- a/php/v3.4/examples/Creatives/CreateTrackingCreative.php +++ /dev/null @@ -1,88 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating tracking creative for advertiser ID %s

', - $values['advertiser_id'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test tracking creative'); - $creative->setType('TRACKING_TEXT'); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('Tracking creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Tracking Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.4/examples/Creatives/GetCreativeFieldValues.php b/php/v3.4/examples/Creatives/GetCreativeFieldValues.php deleted file mode 100755 index 3216daf..0000000 --- a/php/v3.4/examples/Creatives/GetCreativeFieldValues.php +++ /dev/null @@ -1,100 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'field_id', - 'display' => 'Creative Field ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all creative field values for creative field ID %s

', - $values['field_id'] - ); - - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creative Field Values'); - - do { - // Create and execute the creative field values list request. - $response = $this->service->creativeFieldValues->listCreativeFieldValues( - $values['user_profile_id'], - $values['field_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCreativeFieldValues() as $values) { - $this->printResultsTableRow($values); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreativeFieldValues()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creative Field Values'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field Value ID', - 'value' => 'Creative Field Value']; - } -} diff --git a/php/v3.4/examples/Creatives/GetCreativeFields.php b/php/v3.4/examples/Creatives/GetCreativeFields.php deleted file mode 100755 index c0580d5..0000000 --- a/php/v3.4/examples/Creatives/GetCreativeFields.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all creative fields

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creative Fields'); - - do { - // Create and execute the creative fields list request. - $response = $this->service->creativeFields->listCreativeFields( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCreativeFields() as $fields) { - $this->printResultsTableRow($fields); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreativeFields()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creative Fields'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field ID', - 'name' => 'Creative Field Name']; - } -} diff --git a/php/v3.4/examples/Creatives/GetCreativeGroups.php b/php/v3.4/examples/Creatives/GetCreativeGroups.php deleted file mode 100755 index f5ff243..0000000 --- a/php/v3.4/examples/Creatives/GetCreativeGroups.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all creative groups

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creative Groups'); - - do { - // Create and execute the creative fields list request. - $response = $this->service->creativeGroups->listCreativeGroups( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCreativeGroups() as $groups) { - $this->printResultsTableRow($groups); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreativeGroups()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creative Groups'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Group ID', - 'name' => 'Creative Group Name']; - } -} diff --git a/php/v3.4/examples/Creatives/GetCreatives.php b/php/v3.4/examples/Creatives/GetCreatives.php deleted file mode 100755 index 689b3f0..0000000 --- a/php/v3.4/examples/Creatives/GetCreatives.php +++ /dev/null @@ -1,101 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all active creatives for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creatives'); - - do { - // Create and execute the creative fields list request. - $response = $this->service->creatives->listCreatives( - $values['user_profile_id'], - ['active' => true, - 'advertiserId' => $values['advertiser_id'], - 'pageToken' => $pageToken] - ); - - foreach ($response->getCreatives() as $creatives) { - $this->printResultsTableRow($creatives); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreatives()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creatives'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative Type']; - } -} diff --git a/php/v3.4/examples/DimensionValues/GetDimensionValues.php b/php/v3.4/examples/DimensionValues/GetDimensionValues.php deleted file mode 100755 index ec0083e..0000000 --- a/php/v3.4/examples/DimensionValues/GetDimensionValues.php +++ /dev/null @@ -1,96 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'dimension_name', - 'display' => 'Dimension Name', - 'required' => true], - ['name' => 'start_date', - 'display' => 'Start Date (yyyy-MM-dd)', - 'required' => true], - ['name' => 'end_date', - 'display' => 'End Date (yyyy-MM-dd)', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $dimensionValueRequest = - new Google_Service_Dfareporting_DimensionValueRequest(); - $dimensionValueRequest->setDimensionName($values['dimension_name']); - $dimensionValueRequest->setStartDate($values['start_date']); - $dimensionValueRequest->setEndDate($values['end_date']); - - $dimensionValues = $this->service->dimensionValues->query( - $values['user_profile_id'], - $dimensionValueRequest - ); - - printf('

Listing available %s values

', $values['dimension_name']); - - $this->printResultsTable('Dimension Values', $dimensionValues['items']); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Dimension Values'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['value' => 'Dimension Value', - 'id' => 'Dimension ID']; - } -} diff --git a/php/v3.4/examples/Files/CheckFileStatus.php b/php/v3.4/examples/Files/CheckFileStatus.php deleted file mode 100755 index 8d2e4d2..0000000 --- a/php/v3.4/examples/Files/CheckFileStatus.php +++ /dev/null @@ -1,89 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true], - ['name' => 'report_file_id', - 'display' => 'Report File ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Getting status of report file with ID %s

', - $values['report_file_id'] - ); - - $reportFile = $this->service->reports_files->get( - $values['user_profile_id'], - $values['report_id'], - $values['report_file_id'] - ); - - $this->printResultsTable('File status', [$reportFile]); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Check File Generation Status'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status']; - } -} diff --git a/php/v3.4/examples/Files/GetAllFiles.php b/php/v3.4/examples/Files/GetAllFiles.php deleted file mode 100755 index b134ae3..0000000 --- a/php/v3.4/examples/Files/GetAllFiles.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all report files

'; - - $this->printResultsTableHeader('Files'); - - do { - $files = $this->service->files->listFiles( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($files['items'] as $file) { - $url = $file['urls']['browserUrl']; - $file['download'] = 'Link'; - $this->printResultsTableRow($file); - } - - $pageToken = $files['nextPageToken']; - } while (!empty($files['items']) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Files'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status', - 'download' => 'Download']; - } -} diff --git a/php/v3.4/examples/Floodlights/CreateFloodlightActivity.php b/php/v3.4/examples/Floodlights/CreateFloodlightActivity.php deleted file mode 100755 index 5bb5c31..0000000 --- a/php/v3.4/examples/Floodlights/CreateFloodlightActivity.php +++ /dev/null @@ -1,98 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'activity_group_id', - 'display' => 'Floodlight Activity Group ID', - 'required' => true], - ['name' => 'activity_name', - 'display' => 'Floodlight Activity Name', - 'required' => true], - ['name' => 'url', - 'display' => 'Expected URL', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating floodlight activity with name "%s" under group ID' - . ' %s

', - $values['activity_name'], - $values['activity_group_id'] - ); - - $activity = new Google_Service_Dfareporting_FloodlightActivity(); - $activity->setCountingMethod('STANDARD_COUNTING'); - $activity->setExpectedUrl($values['url']); - $activity->setFloodlightActivityGroupId($values['activity_group_id']); - $activity->setFloodlightTagType('GLOBAL_SITE_TAG'); - $activity->setName($values['activity_name']); - - $result = $this->service->floodlightActivities->insert( - $values['user_profile_id'], - $activity - ); - - $this->printResultsTable('Floodlight activity created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Floodlight Activity'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity ID', - 'name' => 'Floodlight Activity Name']; - } -} diff --git a/php/v3.4/examples/Floodlights/CreateFloodlightActivityGroup.php b/php/v3.4/examples/Floodlights/CreateFloodlightActivityGroup.php deleted file mode 100755 index 2fecef3..0000000 --- a/php/v3.4/examples/Floodlights/CreateFloodlightActivityGroup.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'group_name', - 'display' => 'Floodlight Activity Group Name', - 'required' => true], - ['name' => 'configuration_id', - 'display' => 'Floodlight Configuration (Advertiser) ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating floodlight activity group with name "%s"

', - $values['group_name'] - ); - - $group = new Google_Service_Dfareporting_FloodlightActivityGroup(); - $group->setFloodlightConfigurationId($values['configuration_id']); - $group->setName($values['group_name']); - $group->setType('COUNTER'); - - $result = $this->service->floodlightActivityGroups->insert( - $values['user_profile_id'], - $group - ); - - $this->printResultsTable('Floodlight activity group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Floodlight Activity Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity Group ID', - 'name' => 'Floodlight Activity Group Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.4/examples/Floodlights/DownloadFloodlightTags.php b/php/v3.4/examples/Floodlights/DownloadFloodlightTags.php deleted file mode 100755 index 1441677..0000000 --- a/php/v3.4/examples/Floodlights/DownloadFloodlightTags.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Downloading floodlight activity tags for activity ID %s

', - $values['activity_id'] - ); - - $result = $this->service->floodlightActivities->generatetag( - $values['user_profile_id'], - ['floodlightActivityId' => $values['activity_id']] - ); - - // Prepare the tag for display - $activityTag = ''; - if (!is_null($result->getGlobalSiteTagGlobalSnippet())) { - // This is a global site tag, display both the global and event snippets. - $activityTag = sprintf( - "Global site tag global snippet:\n\n%s", - $result->getGlobalSiteTagGlobalSnippet() - ); - $activityTag .= sprintf( - "\n\nGlobal site tag event snippet:\n\n%s", - $result->getFloodlightActivityTag() - ); - } else { - // This is an image or iframe tag. - $activityTag = sprintf( - "Floodlight activity tag:\n\n%s", - $result->getFloodlightActivityTag() - ); - } - - // Display the tag - print str_replace(["\r\n", "\n"], '
', htmlentities($activityTag)); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Download Floodlight Activity Tags'; - } -} diff --git a/php/v3.4/examples/Floodlights/GetFloodlightActivities.php b/php/v3.4/examples/Floodlights/GetFloodlightActivities.php deleted file mode 100755 index dcf7e1b..0000000 --- a/php/v3.4/examples/Floodlights/GetFloodlightActivities.php +++ /dev/null @@ -1,102 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all floodlight activities for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Floodlight Activities'); - - do { - // Create and execute the floodlight activities list request. - $response = - $this->service->floodlightActivities->listFloodlightActivities( - $values['user_profile_id'], - ['advertiserId' => $values['advertiser_id'], - 'pageToken' => $pageToken] - ); - - foreach ($response->getFloodlightActivities() as $activities) { - $this->printResultsTableRow($activities); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getFloodlightActivities()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Floodlight Activities'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity ID', - 'name' => 'Floodlight Activity Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.4/examples/Floodlights/GetFloodlightActivityGroups.php b/php/v3.4/examples/Floodlights/GetFloodlightActivityGroups.php deleted file mode 100755 index 3dce97d..0000000 --- a/php/v3.4/examples/Floodlights/GetFloodlightActivityGroups.php +++ /dev/null @@ -1,103 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all floodlight activity groups for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Floodlight Activity Groups'); - - $activityGroupService = $this->service->floodlightActivityGroups; - - do { - // Create and execute the floodlight activity groups list request. - $response = $activityGroupService->listFloodlightActivityGroups( - $values['user_profile_id'], - ['advertiserId' => $values['advertiser_id'], - 'pageToken' => $pageToken] - ); - - foreach ($response->getFloodlightActivityGroups() as $groups) { - $this->printResultsTableRow($groups); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getFloodlightActivityGroups()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Floodlight Activity Groups'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity Group ID', - 'name' => 'Floodlight Activity Group Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.4/examples/Misc/GetChangeLogsForAdvertiser.php b/php/v3.4/examples/Misc/GetChangeLogsForAdvertiser.php deleted file mode 100755 index 7a8a7ba..0000000 --- a/php/v3.4/examples/Misc/GetChangeLogsForAdvertiser.php +++ /dev/null @@ -1,104 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all change logs for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Change Logs'); - - do { - // Create and execute the change logs list request. - $response = $this->service->changeLogs->listChangeLogs( - $values['user_profile_id'], - ['objectIds' => [$values['advertiser_id']], - 'objectType' => 'OBJECT_ADVERTISER', - 'pageToken' => $pageToken] - ); - - foreach ($response->getChangeLogs() as $log) { - $this->printResultsTableRow($log); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getChangeLogs()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Change Logs For Advertiser'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['action' => 'Action', - 'fieldName' => 'Field', - 'oldValue' => 'Old Value', - 'newValue' => 'New Value']; - } -} diff --git a/php/v3.4/examples/Misc/GetSites.php b/php/v3.4/examples/Misc/GetSites.php deleted file mode 100755 index 5ef571f..0000000 --- a/php/v3.4/examples/Misc/GetSites.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all sites

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Sites'); - - do { - // Create and execute the sites list request. - $response = $this->service->sites->listSites( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getSites() as $sites) { - $this->printResultsTableRow($sites); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getSites()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Sites'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Site ID', - 'keyName' => 'Site Key Name']; - } -} diff --git a/php/v3.4/examples/Misc/GetSize.php b/php/v3.4/examples/Misc/GetSize.php deleted file mode 100755 index 267d868..0000000 --- a/php/v3.4/examples/Misc/GetSize.php +++ /dev/null @@ -1,94 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'width', - 'display' => 'Width (px)', - 'required' => true], - ['name' => 'height', - 'display' => 'Height (px)', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing sizes matching %sx%s

', - $values['width']. $values['height'] - ); - - $this->printResultsTableHeader('Sizes'); - - // Create and execute the size list request. - $response = $this->service->sizes->listSizes( - $values['user_profile_id'], - ['height' => $values['height'], - 'width' => $values['width']] - ); - - foreach ($response->getSizes() as $sizes) { - $this->printResultsTableRow($sizes); - } - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Size'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Size ID', - 'width' => 'Width', - 'height' => 'Height']; - } -} diff --git a/php/v3.4/examples/Placements/CreateContentCategory.php b/php/v3.4/examples/Placements/CreateContentCategory.php deleted file mode 100755 index ffa66ed..0000000 --- a/php/v3.4/examples/Placements/CreateContentCategory.php +++ /dev/null @@ -1,85 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'category_name', - 'display' => 'Content Category Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating content category with name "%s"

', - $values['category_name'] - ); - - $category = new Google_Service_Dfareporting_ContentCategory(); - $category->setName($values['category_name']); - - $result = $this->service->contentCategories->insert( - $values['user_profile_id'], - $category - ); - - $this->printResultsTable('Content category created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Content Category'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Content Category ID', - 'name' => 'Content Category Name']; - } -} diff --git a/php/v3.4/examples/Placements/CreatePlacement.php b/php/v3.4/examples/Placements/CreatePlacement.php deleted file mode 100755 index e6fccd5..0000000 --- a/php/v3.4/examples/Placements/CreatePlacement.php +++ /dev/null @@ -1,122 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'site_id', - 'display' => 'Site ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'placement_name', - 'display' => 'Placement Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating placement with name "%s" under campaign ID %s

', - $values['placement_name'], - $values['campaign_id'] - ); - - // Retrieve the campaign. - $campaign = $this->service->campaigns->get( - $values['user_profile_id'], - $values['campaign_id'] - ); - - $placement = new Google_Service_Dfareporting_Placement(); - $placement->setCampaignId($values['campaign_id']); - $placement->setCompatibility('DISPLAY'); - $placement->setName($values['placement_name']); - $placement->setPaymentSource('PLACEMENT_AGENCY_PAID'); - $placement->setSiteId($values['site_id']); - $placement->setTagFormats(['PLACEMENT_TAG_STANDARD']); - - // Set the size of the placement. - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $placement->setSize($size); - - // Set the pricing schedule for the placement. - $pricingSchedule = new Google_Service_Dfareporting_PricingSchedule(); - $pricingSchedule->setEndDate($campaign->getEndDate()); - $pricingSchedule->setPricingType('PRICING_TYPE_CPM'); - $pricingSchedule->setStartDate($campaign->getStartDate()); - $placement->setPricingSchedule($pricingSchedule); - - // Insert the placement. - $result = $this->service->placements->insert( - $values['user_profile_id'], - $placement - ); - - $this->printResultsTable('Placement created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Placement'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement ID', - 'name' => 'Placement Name']; - } -} diff --git a/php/v3.4/examples/Placements/CreatePlacementGroup.php b/php/v3.4/examples/Placements/CreatePlacementGroup.php deleted file mode 100755 index 8a18378..0000000 --- a/php/v3.4/examples/Placements/CreatePlacementGroup.php +++ /dev/null @@ -1,111 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'site_id', - 'display' => 'Site ID', - 'required' => true], - ['name' => 'group_name', - 'display' => 'Placement Group Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating placement group with name "%s" under campaign ID %s

', - $values['group_name'], - $values['campaign_id'] - ); - - // Retrieve the campaign. - $campaign = $this->service->campaigns->get( - $values['user_profile_id'], - $values['campaign_id'] - ); - - $group = new Google_Service_Dfareporting_PlacementGroup(); - $group->setCampaignId($values['campaign_id']); - $group->setName($values['group_name']); - $group->setPlacementGroupType('PLACEMENT_PACKAGE'); - $group->setSiteId($values['site_id']); - - // Set the pricing schedule for the placement group. - $pricingSchedule = new Google_Service_Dfareporting_PricingSchedule(); - $pricingSchedule->setEndDate($campaign->getEndDate()); - $pricingSchedule->setPricingType('PRICING_TYPE_CPM'); - $pricingSchedule->setStartDate($campaign->getStartDate()); - $group->setPricingSchedule($pricingSchedule); - - // Insert the placement group. - $result = $this->service->placementGroups->insert( - $values['user_profile_id'], - $group - ); - - $this->printResultsTable('Placement group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Placement Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement Group ID', - 'name' => 'Placement Group Name']; - } -} diff --git a/php/v3.4/examples/Placements/CreatePlacementStrategy.php b/php/v3.4/examples/Placements/CreatePlacementStrategy.php deleted file mode 100755 index dbc3077..0000000 --- a/php/v3.4/examples/Placements/CreatePlacementStrategy.php +++ /dev/null @@ -1,85 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'strategy_name', - 'display' => 'Placement Strategy Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating placement strategy with name "%s"

', - $values['strategy_name'] - ); - - $strategy = new Google_Service_Dfareporting_PlacementStrategy(); - $strategy->setName($values['strategy_name']); - - $result = $this->service->placementStrategies->insert( - $values['user_profile_id'], - $strategy - ); - - $this->printResultsTable('Placement strategy created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Placement Strategy'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement Strategy ID', - 'name' => 'Placement Strategy Name']; - } -} diff --git a/php/v3.4/examples/Placements/DownloadPlacementTags.php b/php/v3.4/examples/Placements/DownloadPlacementTags.php deleted file mode 100755 index 6b5ab42..0000000 --- a/php/v3.4/examples/Placements/DownloadPlacementTags.php +++ /dev/null @@ -1,106 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'placement_id', - 'display' => 'Placement ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Downloading placement tags for placement ID %s

', - $values['placement_id'] - ); - - $placementTags = $this->service->placements->generatetags( - $values['user_profile_id'], - ['campaignId' => $values['campaign_id'], - 'placementIds' => [$values['placement_id']], - 'tagFormats' => ['PLACEMENT_TAG_STANDARD', - 'PLACEMENT_TAG_IFRAME_JAVASCRIPT', - 'PLACEMENT_TAG_INTERNAL_REDIRECT'] - ] - ); - - $this->printResultsTableHeader('Placement Tags'); - - foreach ($placementTags['placementTags'] as $placementTag) { - foreach ($placementTag['tagDatas'] as $tagData) { - $result = ['clickTag' => htmlspecialchars($tagData->getClickTag()), - 'format' => $tagData->getFormat(), - 'impressionTag' => - htmlspecialchars($tagData->getImpressionTag())]; - - $this->printResultsTableRow($result); - } - } - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Download Placement Tags'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['format' => 'Format', - 'impressionTag' => 'Impression Tag', - 'clickTag' => 'Click Tag']; - } -} diff --git a/php/v3.4/examples/Placements/GetContentCategories.php b/php/v3.4/examples/Placements/GetContentCategories.php deleted file mode 100755 index 1a69d52..0000000 --- a/php/v3.4/examples/Placements/GetContentCategories.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all content categories

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Content Categories'); - - do { - // Create and execute the content categories list request. - $response = $this->service->contentCategories->listContentCategories( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getContentCategories() as $categories) { - $this->printResultsTableRow($categories); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getContentCategories()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Content Categories'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Content Category ID', - 'name' => 'Content Category Name']; - } -} diff --git a/php/v3.4/examples/Placements/GetPlacementStrategies.php b/php/v3.4/examples/Placements/GetPlacementStrategies.php deleted file mode 100755 index c11f5fc..0000000 --- a/php/v3.4/examples/Placements/GetPlacementStrategies.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all placement strategies

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Placement Strategies'); - - do { - // Create and execute the placement strategies list request. - $response = $this->service->placementStrategies->listPlacementStrategies( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getPlacementStrategies() as $strategies) { - $this->printResultsTableRow($strategies); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getPlacementStrategies()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Placement Strategies'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement Strategy ID', - 'name' => 'Placement Strategy Name']; - } -} diff --git a/php/v3.4/examples/Placements/GetPlacements.php b/php/v3.4/examples/Placements/GetPlacements.php deleted file mode 100755 index 079e0b6..0000000 --- a/php/v3.4/examples/Placements/GetPlacements.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all placements

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Placements'); - - do { - // Create and execute the placements list request. - $response = $this->service->placements->listPlacements( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getPlacements() as $placements) { - $this->printResultsTableRow($placements); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getPlacements()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Placements'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement ID', - 'name' => 'Placement Name', - 'campaignId' => 'Associated Campaign ID']; - } -} diff --git a/php/v3.4/examples/RemarketingLists/CreateRemarketingList.php b/php/v3.4/examples/RemarketingLists/CreateRemarketingList.php deleted file mode 100755 index f361783..0000000 --- a/php/v3.4/examples/RemarketingLists/CreateRemarketingList.php +++ /dev/null @@ -1,122 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true], - ['name' => 'remarketing_list_name', - 'display' => 'Remarketing List Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating remarketing list with name "%s"

', - $values['remarketing_list_name'] - ); - - // Create the remarketing list. - $list = new Google_Service_Dfareporting_RemarketingList(); - $list->setActive(true); - $list->setAdvertiserId($values['advertiser_id']); - $list->setLifeSpan(30); - $list->setName($values['remarketing_list_name']); - - // Create a list population term. - // This term matches all visitors with a U1 value exactly matching - // "test_value". - $term = new Google_Service_Dfareporting_ListPopulationTerm(); - $term->setOperator('STRING_EQUALS'); - $term->setType('CUSTOM_VARIABLE_TERM'); - $term->setValue('test_value'); - $term->setVariableName('U1'); - - // Add the term to a list population clause. - $clause = new Google_Service_Dfareporting_ListPopulationClause(); - $clause->setTerms([$term]); - - // Add the clause to a list population rule. - // This rule will target all visitors who trigger the specified floodlight - // activity and satisfy the custom rule defined in the list population term. - $rule = new Google_Service_Dfareporting_ListPopulationRule(); - $rule->setFloodlightActivityId($values['floodlight_activity_id']); - $rule->setListPopulationClauses([$clause]); - - $list->setListPopulationRule($rule); - - // Insert the remarketing list. - $result = $this->service->remarketingLists->insert( - $values['user_profile_id'], - $list - ); - - $this->printResultsTable('Remarketing list created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Remarketing List'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Remarketing List ID', - 'name' => 'Remarketing List Name']; - } -} diff --git a/php/v3.4/examples/RemarketingLists/GetRemarketingLists.php b/php/v3.4/examples/RemarketingLists/GetRemarketingLists.php deleted file mode 100755 index 7f2117a..0000000 --- a/php/v3.4/examples/RemarketingLists/GetRemarketingLists.php +++ /dev/null @@ -1,104 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all remarketing lists for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Remarketing Lists'); - - do { - // Create and execute the remarketing lists list request. - $response = $this->service->remarketingLists->listRemarketingLists( - $values['user_profile_id'], - $values['advertiser_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getRemarketingLists() as $list) { - $this->printResultsTableRow($list); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getRemarketingLists()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Remarketing Lists'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Remarketing List ID', - 'name' => 'Remarketing List Name']; - } -} diff --git a/php/v3.4/examples/RemarketingLists/ShareRemarketingList.php b/php/v3.4/examples/RemarketingLists/ShareRemarketingList.php deleted file mode 100755 index ca0a17d..0000000 --- a/php/v3.4/examples/RemarketingLists/ShareRemarketingList.php +++ /dev/null @@ -1,108 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'list_id', - 'display' => 'Remarketing List ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Sharing remarketing list %s with advertiser ID %s

', - $values['list_id'], - $values['advertiser_id'] - ); - - // Load the existing share info. - $share = $this->service->remarketingListShares->get( - $values['user_profile_id'], - $values['list_id'] - ); - - $advertiserIds = $share['sharedAdvertiserIds']; - if (!isset($advertiserIds)) { - $advertiserIds = []; - } - - if (!in_array($values['advertiser_id'], $advertiserIds)) { - // Add the specified advertiser to the list of shared advertisers. - $advertiserIds[] = $values['advertiser_id']; - $share->setSharedAdvertiserIds($advertiserIds); - - // Update the share info with the newly added advertiser. - $result = $this->service->remarketingListShares->update( - $values['user_profile_id'], - $share - ); - - $result['advertiserIds'] = implode(',', $result['sharedAdvertiserIds']); - $this->printResultsTable('Remarketing list shared.', [$result]); - } else { - print '
Remarketing list is already shared with advertiser.
'; - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Share Remarketing List With Advertiser'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['remarketingListId' => 'Remarketing List ID', - 'advertiserIds' => 'Shared Advertiser IDs']; - } -} diff --git a/php/v3.4/examples/RemarketingLists/TargetAdToRemarketingList.php b/php/v3.4/examples/RemarketingLists/TargetAdToRemarketingList.php deleted file mode 100755 index 8456727..0000000 --- a/php/v3.4/examples/RemarketingLists/TargetAdToRemarketingList.php +++ /dev/null @@ -1,117 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'ad_id', - 'display' => 'Ad ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Targeting ad %s to a targetable remarketing list.

', - $values['ad_id'] - ); - - // Load the specified ad. - $ad = $this->service->ads->get( - $values['user_profile_id'], - $values['ad_id'] - ); - - // Find a targetable remarketing list for this ad's advertiser. - $listService = $this->service->targetableRemarketingLists; - $lists = $listService->listTargetableRemarketingLists( - $values['user_profile_id'], - $ad['advertiserId'], - ['maxResults' => 1] - ); - - if (!empty($lists['targetableRemarketingLists'])) { - // Select the first targetable remarketing list that was returned. - $list = $lists['targetableRemarketingLists'][0]; - - // Create a list targeting expression. - $expression = new Google_Service_Dfareporting_ListTargetingExpression(); - $expression->setExpression(strval($list['id'])); - - // Update the ad. - $ad->setRemarketingListExpression($expression); - $result = $this->service->ads->update( - $values['user_profile_id'], - $ad - ); - - $result['expression'] = - $result['remarketing_list_expression']['expression']; - - $this->printResultsTable('Ad targeted to remarketing list.', [$result]); - } else { - print '
Ad has no targetable remarketing lists.
'; - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Target Ad to a Remarketing List'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Ad ID', - 'expression' => 'Remarketing List Expression']; - } -} diff --git a/php/v3.4/examples/Reports/CreateStandardReport.php b/php/v3.4/examples/Reports/CreateStandardReport.php deleted file mode 100755 index f2e69e4..0000000 --- a/php/v3.4/examples/Reports/CreateStandardReport.php +++ /dev/null @@ -1,186 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Creating a new standard report

'; - $this->flush(); - - $userProfileId = $values['user_profile_id']; - - // 1. Create a report resource. - $report = $this->createReportResource(); - - // 2. Define the report criteria. - $this->defineReportCriteria($report); - - // 3. (optional) Look up compatible fields. - $this->findCompatibleFields($userProfileId, $report); - - // 4. Add dimension filters to the report criteria. - $this->addDimensionFilters($userProfileId, $report); - - // 5. Save the report resource. - $report = $this->insertReportResource($userProfileId, $report); - - $this->printResultsTable('Standard Report', [$report]); - } - - private function createReportResource() - { - $report = new Google_Service_Dfareporting_Report(); - - // Set the required fields "name" and "type". - $report->setName('Example standard report'); - $report->setType('STANDARD'); - - // Set optional fields. - $report->setFileName('example_report'); - $report->setFormat('CSV'); - - return $report; - } - - private function defineReportCriteria($report) - { - // Define a date range to report on. This example uses explicit start and - // end dates to mimic the "LAST_30_DAYS" relative date range. - $dateRange = new Google_Service_Dfareporting_DateRange(); - $dateRange->setStartDate( - date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 30, date('Y'))) - ); - $dateRange->setEndDate(date('Y-m-d')); - - // Create a report criteria. - $dimension = new Google_Service_Dfareporting_SortedDimension(); - $dimension->setName('advertiser'); - - $criteria = new Google_Service_Dfareporting_ReportCriteria(); - $criteria->setDateRange($dateRange); - $criteria->setDimensions([$dimension]); - $criteria->setMetricNames(['clicks', 'impressions']); - - // Add the criteria to the report resource. - $report->setCriteria($criteria); - } - - private function findCompatibleFields($userProfileId, $report) - { - $fields = $this->service->reports_compatibleFields->query( - $userProfileId, - $report - ); - - $reportFields = $fields->getReportCompatibleFields(); - - if (!empty($reportFields->getDimensions())) { - // Add a compatible dimension to the report. - $dimension = $reportFields->getDimensions()[0]; - $sortedDimension = new Google_Service_Dfareporting_SortedDimension(); - $sortedDimension->setName($dimension->getName()); - $report->getCriteria()->setDimensions( - array_merge( - $report->getCriteria()->getDimensions(), - [$sortedDimension] - ) - ); - } elseif (!empty($reportFields->getMetrics())) { - // Add a compatible metric to the report. - $metric = $reportFields->getMetrics()[0]; - $report->getCriteria()->setMetricNames( - array_merge( - $report->getCriteria()->getMetricNames(), - [$metric->getName()] - ) - ); - } - } - - private function addDimensionFilters($userProfileId, $report) - { - // Query advertiser dimension values for report run dates. - $request = new Google_Service_Dfareporting_DimensionValueRequest(); - $request->setStartDate( - $report->getCriteria()->getDateRange()->getStartDate() - ); - $request->setEndDate( - $report->getCriteria()->getDateRange()->getEndDate() - ); - $request->setDimensionName('advertiser'); - - $values = - $this->service->dimensionValues->query($userProfileId, $request); - - if (!empty($values->getItems())) { - // Add a value as a filter to the report criteria. - $report->getCriteria()->setDimensionFilters([$values->getItems()[0]]); - } - } - - private function insertReportResource($userProfileId, $report) - { - $insertedReport = - $this->service->reports->insert($userProfileId, $report); - return $insertedReport; - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Standard Report'; - } - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Report ID', - 'name' => 'Report Name']; - } -} diff --git a/php/v3.4/examples/Reports/DeleteReport.php b/php/v3.4/examples/Reports/DeleteReport.php deleted file mode 100755 index 5cbc480..0000000 --- a/php/v3.4/examples/Reports/DeleteReport.php +++ /dev/null @@ -1,68 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf('

Deleting report with ID %s

', $values['report_id']); - - $this->service->reports->delete( - $values['user_profile_id'], - $values['report_id'] - ); - - print '
Success
'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Delete Report'; - } -} diff --git a/php/v3.4/examples/Reports/DownloadReportFile.php b/php/v3.4/examples/Reports/DownloadReportFile.php deleted file mode 100755 index ef72ddf..0000000 --- a/php/v3.4/examples/Reports/DownloadReportFile.php +++ /dev/null @@ -1,180 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true], - ['name' => 'file_id', - 'display' => 'Report File ID']]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $reportId = $values['report_id']; - $userProfileId = $values['user_profile_id']; - - // 1. Find a file to download. - $fileId = $values['file_id']; - if (empty($fileId)) { - $fileId = $this->findFile($userProfileId, $reportId); - } - - if (!empty($fileId)) { - printf( - '

Retrieving contents of file %d for report %d

', - $fileId, - $reportId - ); - $this->flush(); - - // 2. (optional) Generate browser URL. - $this->generateBrowserUrl($reportId, $fileId); - $this->flush(); - - // 3. Directly download the file. - $this->directDownloadFile($reportId, $fileId); - } else { - printf( - '

No file found for profile ID %d and report ID %d

', - $userProfileId, - $reportId - ); - } - } - - private function findFile($userProfileId, $reportId) - { - $target = null; - $response = null; - $pageToken = null; - - do { - // Create and execute the file list request. - $response = $this->service->reports_files->listReportsFiles( - $userProfileId, - $reportId, - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $file) { - if ($this->isTargetFile($file)) { - $target = $file; - break; - } - } - - $pageToken = $response->getNextPageToken(); - } while (empty($target) && !empty($response->getItems()) && !empty($pageToken)); - - return is_null($target) ? null : $target->getId(); - } - - private function isTargetFile($file) - { - // Provide custom validation logic here. - // For example purposes, any file with REPORT_AVAILABLE status is - // considered valid. - return $file->getStatus() === 'REPORT_AVAILABLE'; - } - - private function generateBrowserUrl($reportId, $fileId) - { - $file = $this->service->files->get($reportId, $fileId); - $browserUrl = $file->getUrls()->getBrowserUrl(); - - printf( - '

Report file has browser URL: %s

', - $browserUrl, - $browserUrl - ); - } - - private function directDownloadFile($reportId, $fileId) - { - // Retrieve the file metadata. - $file = $this->service->files->get($reportId, $fileId); - - if ($file->getStatus() === 'REPORT_AVAILABLE') { - try { - // Prepare a local file to download the report contents to. - $fileName = join( - DIRECTORY_SEPARATOR, - [sys_get_temp_dir(), $this->generateFileName($file)] - ); - $fileResource = fopen($fileName, 'w+'); - $fileStream = \GuzzleHttp\Psr7\stream_for($fileResource); - - // Execute the get request and download the file. - $httpClient = $this->service->getClient()->authorize(); - $result = $httpClient->request( - 'GET', - $file->getUrls()->getApiUrl(), - [\GuzzleHttp\RequestOptions::SINK => $fileStream] - ); - - printf('

Report file saved to: %s

', $fileName); - print '

Report file contents:

'; - print nl2br(file_get_contents($fileName)); - } finally { - $fileStream->close(); - fclose($fileResource); - } - } - } - - private function generateFileName($file) - { - $fileName = $file->getFileName() ?: $file->getId(); - $extension = $file->getFormat() === 'CSV' ? '.csv' : '.xls'; - - return $fileName . $extension; - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Download Report File'; - } -} diff --git a/php/v3.4/examples/Reports/GenerateReportFile.php b/php/v3.4/examples/Reports/GenerateReportFile.php deleted file mode 100755 index c6fab12..0000000 --- a/php/v3.4/examples/Reports/GenerateReportFile.php +++ /dev/null @@ -1,210 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID']]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $userProfileId = $values['user_profile_id']; - - // 1. Find a report to run. - $reportId = $values['report_id']; - if (empty($reportId)) { - $reportId = $this->findReport($userProfileId); - } - - if (!empty($reportId)) { - printf( - '

Generating a report file for report with ID %d

', - $reportId - ); - $this->flush(); - - // 2. Run the report. - $file = $this->runReport($userProfileId, $reportId); - $this->flush(); - - // 3. Wait for the report file to be ready. - $file = $this->waitForReportFile($reportId, $file->getId()); - $this->flush(); - - if (!empty($file)) { - $this->printResultsTable('Report File', [$file]); - } - } else { - printf('

No report found for profile ID %d

', $userProfileId); - } - } - - private function findReport($userProfileId) - { - $target = null; - $response = null; - $pageToken = null; - - do { - // Create and execute the report list request. - $response = $this->service->reports->listReports( - $userProfileId, - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $report) { - if ($this->isTargetReport($report)) { - $target = $report; - break; - } - } - - $pageToken = $response->getNextPageToken(); - } while (empty($target) && !empty($response->getItems()) && !empty($pageToken)); - - return is_null($target) ? null : $target->getId(); - } - - private function isTargetReport($file) - { - // Provide custom validation logic here. - // For example purposes, any report is considered valid. - return true; - } - - private function runReport($userProfileId, $reportId) - { - // Run the report. - $file = $this->service->reports->run($userProfileId, $reportId); - - printf( - 'Running report %d, current file status is %s
', - $reportId, - $file->getStatus() - ); - return $file; - } - - private function waitForReportFile($reportId, $fileId) - { - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve - // quota. - $sleep = 0; - $startTime = time(); - - do { - $file = $this->service->files->get($reportId, $fileId); - - if ($file->getStatus() === 'REPORT_AVAILABLE') { - printf('File status is %s, ready to download
', $file->getStatus()); - return $file; - } elseif ($file->getStatus() !== 'PROCESSING') { - printf('File status is %s, processing failed
', $file->getStatus()); - return null; - } elseif (time() - $startTime > self::MAX_RETRY_ELAPSED_TIME) { - printf('File processing deadline exceeded
'); - return null; - } - - $sleep = $this->getNextSleepInterval($sleep); - printf( - 'File status is %s, sleeping for %d seconds
', - $file->getStatus(), - $sleep - ); - $this->sleep($sleep); - } while (true); - } - - private function getNextSleepInterval($previousSleepInterval) - { - $minInterval = max(self::MIN_RETRY_INTERVAL, $previousSleepInterval); - $maxInterval = max(self::MIN_RETRY_INTERVAL, $previousSleepInterval * 3); - return min(self::MAX_RETRY_INTERVAL, rand($minInterval, $maxInterval)); - } - - private function sleep($interval) - { - $startTime = time(); - do { - // Flush regularly to prevent timeouts. - $this->flush(); - sleep(1); - - if (time() - $startTime >= $interval) { - return; - } - } while (true); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Generate Report File'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status']; - } -} diff --git a/php/v3.4/examples/Reports/GetAllReportFiles.php b/php/v3.4/examples/Reports/GetAllReportFiles.php deleted file mode 100755 index f0d4653..0000000 --- a/php/v3.4/examples/Reports/GetAllReportFiles.php +++ /dev/null @@ -1,101 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all files for report with ID %s

', - $values['report_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Report Files'); - - do { - $response = $this->service->reports_files->listReportsFiles( - $values['user_profile_id'], - $values['report_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $file) { - $file['apiUrl'] = $file->getUrls()->getApiUrl(); - $this->printResultsTableRow($file); - } - - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getItems()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Report Files'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status', - 'apiUrl' => 'API URL']; - } -} diff --git a/php/v3.4/examples/Reports/GetAllReports.php b/php/v3.4/examples/Reports/GetAllReports.php deleted file mode 100755 index adb89b1..0000000 --- a/php/v3.4/examples/Reports/GetAllReports.php +++ /dev/null @@ -1,90 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all reports

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Reports'); - do { - $response = $this->service->reports->listReports( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $report) { - $this->printResultsTableRow($report); - } - - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getItems()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Reports'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Report ID', - 'name' => 'Report Name', - 'type' => 'Report Type']; - } -} diff --git a/php/v3.4/examples/Reports/GetCompatibleFields.php b/php/v3.4/examples/Reports/GetCompatibleFields.php deleted file mode 100755 index 8f2cd32..0000000 --- a/php/v3.4/examples/Reports/GetCompatibleFields.php +++ /dev/null @@ -1,110 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing compatible fields for report with ID %s

', - $values['report_id'] - ); - - // Retrieve the specified report - $report = $this->service->reports->get( - $values['user_profile_id'], - $values['report_id'] - ); - - // Look up the compatible fields for this report - $fields = $this->service->reports_compatibleFields->query( - $values['user_profile_id'], - $report - ); - - // Print the compatible dimensions - $this->printResultsTable( - 'Dimensions', - $fields->getReportCompatibleFields()->getDimensions() - ); - - // Print the compatible metrics - $this->printResultsTable( - 'Metrics', - $fields->getReportCompatibleFields()->getMetrics() - ); - - // Print the compatible dimension filters - $this->printResultsTable( - 'Dimension Filters', - $fields->getReportCompatibleFields()->getDimensionFilters() - ); - - // Print the compatible pivoted activity metrics - $this->printResultsTable( - 'Pivoted Activity Metrics', - $fields->getReportCompatibleFields()->getPivotedActivityMetrics() - ); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Compatible Fields'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['name' => 'Field Name']; - } -} diff --git a/php/v3.4/examples/Subaccounts/CreateSubaccount.php b/php/v3.4/examples/Subaccounts/CreateSubaccount.php deleted file mode 100755 index a5e05fb..0000000 --- a/php/v3.4/examples/Subaccounts/CreateSubaccount.php +++ /dev/null @@ -1,99 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'account_id', - 'display' => 'Account ID', - 'required' => true], - ['name' => 'permission_one', - 'display' => 'First Permission ID', - 'required' => true], - ['name' => 'permission_two', - 'display' => 'Second Permission ID', - 'required' => true], - ['name' => 'subaccount_name', - 'display' => 'Subaccount Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating subaccount with name "%s" for account ID %s

', - $values['subaccount_name'], - $values['account_id'] - ); - - $subaccount = new Google_Service_Dfareporting_Subaccount(); - $subaccount->setName($values['subaccount_name']); - $subaccount->setAvailablePermissionIds( - [$values['permission_one'], $values['permission_two']] - ); - - $result = $this->service->subaccounts->insert( - $values['user_profile_id'], - $subaccount - ); - - $this->printResultsTable('Subaccount created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Subaccount'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Subaccount ID', - 'name' => 'Subaccount Name']; - } -} diff --git a/php/v3.4/examples/Subaccounts/GetSubaccountPermissions.php b/php/v3.4/examples/Subaccounts/GetSubaccountPermissions.php deleted file mode 100755 index 8370a99..0000000 --- a/php/v3.4/examples/Subaccounts/GetSubaccountPermissions.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'subaccount_id', - 'display' => 'Subaccount ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $subaccount = $this->service->subaccounts->get( - $values['user_profile_id'], - $values['subaccount_id'] - ); - - printf( - '

Listing all permissions for subaccount "%s"

', - $subaccount->getName() - ); - - $permissions = - $this->service->userRolePermissions->listUserRolePermissions( - $values['user_profile_id'], - ['ids' => $subaccount->getAvailablePermissionIds()] - ); - - $this->printResultsTable('Subaccount Permissions', $permissions); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Subaccount Permissions'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Permission ID', - 'name' => 'Permission Name']; - } -} diff --git a/php/v3.4/examples/Subaccounts/GetSubaccounts.php b/php/v3.4/examples/Subaccounts/GetSubaccounts.php deleted file mode 100755 index 28df915..0000000 --- a/php/v3.4/examples/Subaccounts/GetSubaccounts.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all subaccounts

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Subaccounts'); - - do { - // Create and execute the subaccounts list request. - $response = $this->service->subaccounts->listSubaccounts( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getSubaccounts() as $subaccount) { - $this->printResultsTableRow($subaccount); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getSubaccounts()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Subaccounts'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Subaccount ID', - 'name' => 'Subaccount Name']; - } -} diff --git a/php/v3.4/examples/TargetingTemplates/ConfigureDynamicAssetSelection.php b/php/v3.4/examples/TargetingTemplates/ConfigureDynamicAssetSelection.php deleted file mode 100755 index 2bacb71..0000000 --- a/php/v3.4/examples/TargetingTemplates/ConfigureDynamicAssetSelection.php +++ /dev/null @@ -1,158 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'creative_id', - 'display' => 'In-stream Video Creative ID', - 'required' => true], - ['name' => 'template_id', - 'display' => 'Targeting Template ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Video Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Configuring dynamic asset selection for creative ID %s

', - $values['creative_id'] - ); - - // Retrieve the specified creative. - $creative = $this->service->creatives->get( - $values['user_profile_id'], - $values['creative_id'] - ); - if (is_null($creative) || strcmp($creative->getType(), 'INSTREAM_VIDEO') !== 0) { - print 'Invalid creative specified.'; - return; - } - - $assetSelection = $creative->getCreativeAssetSelection(); - if (!$creative->getDynamicAssetSelection()) { - // Locate an existing video asset to use as a default. - // This example uses the first PARENT_VIDEO asset found. - $defaultVideoAssetId = $this->findDefaultVideoAssetId($creative); - if ($defaultVideoAssetId < 0) { - print 'Default video asset could not be found.'; - return; - } - - // Create a new selection using the existing asset as a default. - $assetSelection = - new Google_Service_Dfareporting_CreativeAssetSelection(); - $assetSelection->setDefaultAssetId($defaultVideoAssetId); - $assetSelection->setRules([]); - - // Enable dynamic asset selection for the creative. - $creative->setDynamicAssetSelection(true); - $creative->setCreativeAssetSelection($assetSelection); - } - - // Upload the new video asset and add it to the creative. - $video = uploadAsset( - $this->service, - $values['user_profile_id'], - $creative->getAdvertiserId(), - $values['asset_file'], - 'VIDEO' - ); - $videoAsset = new Google_Service_Dfareporting_CreativeAsset(); - $videoAsset->setAssetIdentifier($video->getAssetIdentifier()); - $videoAsset->setRole('PARENT_VIDEO'); - $creative->setCreativeAssets( - array_merge($creative->getCreativeAssets(), [$videoAsset]) - ); - - // Create a rule targeting the new video asset and add it to the selection. - $rule = new Google_Service_Dfareporting_Rule(); - $rule->setAssetId($video->getId()); - $rule->setName('Test rule for asset ' . $video->getId()); - $rule->setTargetingTemplateId($values['template_id']); - $assetSelection->setRules( - array_merge($assetSelection->getRules(), [$rule]) - ); - - // Update the creative. - $result = $this->service->creatives->update( - $values['user_profile_id'], - $creative - ); - - printf( - 'Dynamic asset selection enabled for creative with ID %d.', - $result->getId() - ); - } - - private function findDefaultVideoAssetId($creative) - { - $assets = $creative->getCreativeAssets(); - $index = array_search( - 'PARENT_VIDEO', - array_map( - function ($asset) { - return $asset->getRole(); - }, - $assets - ) - ); - - return $index !== false ? $assets[$index]->getId() : -1; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Configure Dynamic Asset Targeting'; - } -} diff --git a/php/v3.4/examples/TargetingTemplates/CreateTargetingTemplate.php b/php/v3.4/examples/TargetingTemplates/CreateTargetingTemplate.php deleted file mode 100755 index cf1131a..0000000 --- a/php/v3.4/examples/TargetingTemplates/CreateTargetingTemplate.php +++ /dev/null @@ -1,100 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'template_name', - 'display' => 'Template Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating targeting template "%s" for advertiser ID %s

', - $values['template_name'], - $values['advertiser_id'] - ); - - // Create the targeting template. - $template = new Google_Service_Dfareporting_TargetingTemplate(); - $template->setAdvertiserId($values['advertiser_id']); - $template->setName($values['template_name']); - - // Configure the template to serve ads on Monday, Wednesday, and Friday from - // 9 to 10am and 3 to 5pm. - $targeting = new Google_Service_Dfareporting_DayPartTargeting(); - $targeting->setDaysOfWeek(['MONDAY', 'WEDNESDAY', 'FRIDAY']); - $targeting->setHoursOfDay([9, 15, 16]); - $targeting->setUserLocalTime(true); - $template->setDayPartTargeting($targeting); - - $result = $this->service->targetingTemplates->insert( - $values['user_profile_id'], - $template - ); - - $this->printResultsTable('Targeting template created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Targeting Template'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Template ID', - 'name' => 'Template Name']; - } -} diff --git a/php/v3.4/examples/TargetingTemplates/GetTargetingTemplates.php b/php/v3.4/examples/TargetingTemplates/GetTargetingTemplates.php deleted file mode 100755 index f7051c5..0000000 --- a/php/v3.4/examples/TargetingTemplates/GetTargetingTemplates.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all targeting templates

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Targeting Templates'); - - do { - // Create and execute the targeting templates list request. - $response = $this->service->targetingTemplates->listTargetingTemplates( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getTargetingTemplates() as $template) { - $this->printResultsTableRow($template); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getTargetingTemplates()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Targeting Templates'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Template ID', - 'name' => 'Template Name', - 'advertiserId' => 'Advertiser ID']; - } -} diff --git a/php/v3.4/examples/UserProfiles/GetAllUserProfiles.php b/php/v3.4/examples/UserProfiles/GetAllUserProfiles.php deleted file mode 100755 index 336a53a..0000000 --- a/php/v3.4/examples/UserProfiles/GetAllUserProfiles.php +++ /dev/null @@ -1,64 +0,0 @@ -service->userProfiles->listUserProfiles(); - - print '

Listing of User Profiles associated with your account

'; - - $this->printResultsTable('User Profiles', $result['items']); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All User Profiles'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['profileId' => 'Profile ID', - 'userName' => 'User Name', - 'accountId' => 'Account ID', - 'accountName' => 'Account Name', - 'subAccountId' => 'Subaccount ID', - 'subAccountName' => 'Subaccount Name']; - } -} diff --git a/php/v3.4/examples/UserRoles/CreateUserRole.php b/php/v3.4/examples/UserRoles/CreateUserRole.php deleted file mode 100755 index fb2a4ff..0000000 --- a/php/v3.4/examples/UserRoles/CreateUserRole.php +++ /dev/null @@ -1,106 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'parent_user_role_id', - 'display' => 'Parent User Role ID', - 'required' => true], - ['name' => 'subaccount_id', - 'display' => 'Subaccount ID', - 'required' => true], - ['name' => 'permission_one', - 'display' => 'First Permission ID', - 'required' => true], - ['name' => 'permission_two', - 'display' => 'Second Permission ID', - 'required' => true], - ['name' => 'user_role_name', - 'display' => 'User Role Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating user role with name "%s" under parent role ID %s

', - $values['user_role_name'], - $values['parent_user_role_id'] - ); - - $userRole = new Google_Service_Dfareporting_UserRole(); - $userRole->setName($values['user_role_name']); - $userRole->setParentUserRoleId($values['parent_user_role_id']); - $userRole->setPermissions( - [$values['permission_one'], $values['permission_two']] - ); - $userRole->setSubaccountId($values['subaccount_id']); - - $result = $this->service->userRoles->insert( - $values['user_profile_id'], - $userRole - ); - - $this->printResultsTable('User role created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create User Role'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'User Role ID', - 'name' => 'User Role Name']; - } -} diff --git a/php/v3.4/examples/UserRoles/GetUserRoles.php b/php/v3.4/examples/UserRoles/GetUserRoles.php deleted file mode 100755 index c7ecece..0000000 --- a/php/v3.4/examples/UserRoles/GetUserRoles.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all user roles

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('User Roles'); - - do { - // Create and execute the subaccounts list request. - $response = $this->service->userRoles->listUserRoles( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getUserRoles() as $userRoles) { - $this->printResultsTableRow($userRoles); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getUserRoles()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All User Roles'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'User Role ID', - 'name' => 'User Role Name']; - } -} diff --git a/php/v3.4/htmlHelper.php b/php/v3.4/htmlHelper.php deleted file mode 100755 index 8bf2486..0000000 --- a/php/v3.4/htmlHelper.php +++ /dev/null @@ -1,81 +0,0 @@ -'; - print ''; - printf('%s', $htmlTitle); - print ''; - print ''; -} - -/** - * Closes the HTML. - */ -function printHtmlFooter() -{ - print ''; - print ''; -} - -/** - * Closes the HTML for samples. - */ -function printSampleHtmlFooter() -{ - print '
Go back to samples list'; - printHtmlFooter(); -} - -/** - * Prints the index with links to the examples. - * @param array $actions supported actions - */ -function printExamplesIndex($actions) -{ - print '

Select a sample from the list

'; - print ''; -} diff --git a/php/v3.4/index.php b/php/v3.4/index.php deleted file mode 100755 index d59533f..0000000 --- a/php/v3.4/index.php +++ /dev/null @@ -1,201 +0,0 @@ -setApplicationName( - 'DCM/DFA Reporting and Trafficking API PHP Samples' -); -$client->addScope(Google_Service_Dfareporting::DFAREPORTING); -$client->addScope(Google_Service_Dfareporting::DFATRAFFICKING); -$client->addScope(Google_Service_Dfareporting::DDMCONVERSIONS); -$client->setAccessType('offline'); - -if (getenv('GOOGLE_APPLICATION_CREDENTIALS')) { - $client->useApplicationDefaultCredentials(); -} else { - // Be sure to replace the contents of client_secrets.json with your developer - // credentials. - $client->setAuthConfigFile('client_secrets.json'); -} - -// Create service. -$service = new Google_Service_Dfareporting($client); - -// If we're logging out we just need to clear our local access token. -// Note that this only logs you out of the session. If STORE_ON_DISK is -// enabled and you want to remove stored data, delete the file. -if (isset($_REQUEST['logout'])) { - unset($_SESSION['access_token']); -} - -// If we have a code back from the OAuth 2.0 flow, we need to exchange that -// with the authenticate() function. We store the resultant access token -// bundle in the session (and disk, if enabled), and redirect to this page. -if (isset($_GET['code'])) { - $client->authenticate($_GET['code']); - // Note that "getAccessToken" actually retrieves both the access and refresh - // tokens, assuming both are available. - $_SESSION['access_token'] = $client->getAccessToken(); - if (STORE_ON_DISK) { - file_put_contents(TOKEN_FILENAME, json_encode($_SESSION['access_token'])); - } - $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; - header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); - exit; -} - -// If we have an access token, we can make requests, else we generate an -// authentication URL. -if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { - $client->setAccessToken($_SESSION['access_token']); -} elseif (STORE_ON_DISK && file_exists(TOKEN_FILENAME) && - filesize(TOKEN_FILENAME) > 0) { - // Note that "setAccessToken" actually sets both the access and refresh token, - // assuming both were saved. - $client->setAccessToken(file_get_contents(TOKEN_FILENAME)); - $_SESSION['access_token'] = $client->getAccessToken(); -} else { - // If we're doing disk storage, generate a URL that forces user approval. - // This is the only way to guarantee we get back a refresh token. - if (STORE_ON_DISK) { - $client->setApprovalPrompt('force'); - } - $authUrl = $client->createAuthUrl(); -} - -$pageTitle = sprintf( - 'DCM/DFA Reporting and Trafficking API %s PHP usage samples', - $service->version -); -printHtmlHeader($pageTitle); - -if (isset($authUrl)) { - // No access token found, show the link to generate one - printf("", $authUrl); -} else { - print "Logout"; -} - -if ($client->getAccessToken()) { - // If the action is set, dispatch the action if supported - if (isset($_GET['action'])) { - $action = decodeActionString($_GET['action']); - if (!isValidAction($action)) { - die('Unsupported action: ' . $_GET['action'] . "\n"); - } - - displayAction($action); - } else { - // Show the list of links to supported actions. - printExamplesIndex(getSupportedActions()); - printHtmlFooter(); - } - - // Note that we re-store the access_token bundle, just in case anything - // changed during the request - the main thing that might happen here is the - // access token itself is refreshed if the application has offline access. - $_SESSION['access_token'] = $client->getAccessToken(); -} - -/** - * Displays the requested action. - */ -function displayAction($action) -{ - global $service; - - // Render the required action. - include_once 'examples/' . $action[0] . '/' . $action[1] . '.php'; - $class = $action[1]; - $example = new $class($service); - printHtmlHeader($example->getName()); - try { - $example->execute(); - } catch (Google_Exception $ex) { - print_r($ex); - print 'An error as occurred while calling the example:
'; - print $ex->getMessage(); - } - printSampleHtmlFooter(); -} - -/** - * Determines whether the requested action is in our list of supported actions. - */ -function isValidAction($action) -{ - $actions = getSupportedActions(); - - if (array_key_exists($action[0], $actions)) { - $section = $actions[$action[0]]; - if (in_array($action[1], $section)) { - return true; - } - } - - return false; -} - -/** - * Decodes an action string passed as a URL parameter into a section and action - * pair. - */ -function decodeActionString($actionString) -{ - $parts = explode(':', $actionString); - if (count($parts) != 2) { - die('Invalid action specified.'); - } - - return $parts; -} - -/** - * Builds an array containing the supported actions, separated into sections. - */ -function getSupportedActions() -{ - $actions = []; - - foreach (glob('examples/*/*.php') as $file) { - $dir = dirname($file); - $section = substr($dir, strrpos($dir, '/') + 1); - - if (!array_key_exists($section, $actions)) { - $actions[$section] = []; - } - - $actions[$section][] = basename($file, '.php'); - } - - return $actions; -} diff --git a/php/v3.4/styles/style.css b/php/v3.4/styles/style.css deleted file mode 100755 index c64bc3b..0000000 --- a/php/v3.4/styles/style.css +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -a { - font-size: .9em; - color: black; -} - -table, th, td { - border: 1px solid black; -} - -ul { - list-style: none; -} - -.nav { - padding-left: 0; -} - -.noResults { - font-weight: bold; - text-align: center; -} - diff --git a/php/v3.5/README.md b/php/v3.5/README.md deleted file mode 100644 index 773cec4..0000000 --- a/php/v3.5/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# DCM/DFA Reporting and Trafficking API PHP Samples - -This is a collection of samples written in PHP which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - - - PHP 5.4+ - - JSON PHP extension - - Composer - -From the example directory, run `composer install` to install all dependencies. - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Overview screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" -> "OAuth2 client ID" - - Select "Web Application" as the "Application type" - - Configure javascript origins and redirect URIs - - Authorized Javascript Origins: http://localhost - - Authorized Redirect URIs: http://localhost/path/to/index.php - - Click "Create client ID" - - Click "Download JSON" and save the file as `client_secrets.json` in your - examples directory - -> #### Security alert! - -> Always ensure that your client_secrets.json file is not publicly accessible. -> This file contains credential information which could allow unauthorized access -> to your DFA account. - -## Running the Examples - -I'm assuming you've checked out the code and are reading this from a local -directory. If not check out the code to a local directory. - -1. Open the sample (`http://your/path/index.php`) in your browser - -2. Complete the authorization steps - -3. Select an example and provide the required information - -3. Examine the response, be inspired and start hacking an amazing new app! diff --git a/php/v3.5/auth/AuthenticateUsingServiceAccount.php b/php/v3.5/auth/AuthenticateUsingServiceAccount.php deleted file mode 100644 index aeb867a..0000000 --- a/php/v3.5/auth/AuthenticateUsingServiceAccount.php +++ /dev/null @@ -1,102 +0,0 @@ - - * - * This optional flag only applies to service accounts which have domain-wide - * delegation enabled and wish to make API requests on behalf of an account - * within that domain. Using this flag will not allow you to impersonate a user - * from a domain that you don't own (e.g., gmail.com). - */ -class AuthenticateUsingServiceAccount -{ - // The OAuth 2.0 scopes to request. - private static $OAUTH_SCOPES = [ - Google_Service_Dfareporting::DFAREPORTING - ]; - - public function run($pathToJsonFile, $email = null) - { - // Create an authenticated client object. - $client = $this->createAuthenticatedClient($pathToJsonFile, $email); - - // Create a Dfareporting service object. - $service = new Google_Service_Dfareporting($client); - - $this->getUserProfiles($service); - } - - private function createAuthenticatedClient($pathToJsonFile, $email) - { - // Create a Google_Client instance. - // - // Note: application name should be replaced with a value that identifies - // your application. Suggested format is "MyCompany-ProductName". - $client = new Google_Client(); - $client->setApplicationName('PHP service account sample'); - $client->setScopes(self::$OAUTH_SCOPES); - - // Load the service account credentials. - $client->setAuthConfig($pathToJsonFile); - - // Configure impersonation (if applicable). - if (!is_null($email)) { - $client->setSubject($email); - } - - return $client; - } - - private function getUserProfiles($service) - { - // Retrieve and print all user profiles for the current authorized user. - $result = $service->userProfiles->listUserProfiles(); - foreach ($result['items'] as $userProfile) { - printf( - "User profile \"%s\" (ID: %d) found for account %d.\n", - $userProfile->getUserName(), - $userProfile->getProfileId(), - $userProfile->getAccountId() - ); - } - } -} - -if ($argc < 2 || $argc >= 4) { - printf( - "Usage: %s /path/to/client_secrets.json [email_to_impersonate]\n", - $argv[0] - ); -} else { - $sample = new AuthenticateUsingServiceAccount(); - - if ($argc == 2) { - $sample->run($argv[1]); - } else { - $sample->run($argv[1], $argv[2]); - } -} diff --git a/php/v3.5/auth/AuthenticateUsingUserAccount.php b/php/v3.5/auth/AuthenticateUsingUserAccount.php deleted file mode 100644 index 0c3a003..0000000 --- a/php/v3.5/auth/AuthenticateUsingUserAccount.php +++ /dev/null @@ -1,110 +0,0 @@ -createAuthenticatedClient( - $pathToJsonFile, - self::TOKEN_STORE - ); - - // Create a Dfareporting service object. - $service = new Google_Service_Dfareporting($client); - - $this->getUserProfiles($service); - } - - private function createAuthenticatedClient($pathToJsonFile, $tokenStore) - { - // Create a Google_Client instance. - // - // Note: application name should be replaced with a value that identifies - // your application. Suggested format is "MyCompany-ProductName". - $client = new Google_Client(); - $client->setAccessType('offline'); - $client->setApplicationName('PHP installed app sample'); - $client->setRedirectUri(self::OAUTH_REDIRECT_URI); - $client->setScopes(self::$OAUTH_SCOPES); - - // Load the client secrets file. - $client->setAuthConfig($pathToJsonFile); - - // Try to load cached credentials from the token store. Using a token store - // allows auth credentials to be cached, so they survive multiple runs of - // the application. This avoids prompting the user for authorization every - // time the access token expires, by remembering the refresh token. - if (file_exists($tokenStore) && filesize($tokenStore) > 0) { - $client->setAccessToken(file_get_contents($tokenStore)); - } else { - // If no cached credentials were found, authorize and persist - // credentials to the token store. - print 'Open this URL in your browser and authorize the application.'; - printf("\n\n%s\n\n", $client->createAuthUrl()); - print 'Enter the authorization code: '; - $code = trim(fgets(STDIN)); - $client->authenticate($code); - - file_put_contents($tokenStore, json_encode($client->getAccessToken())); - } - - return $client; - } - - private function getUserProfiles($service) - { - // Retrieve and print all user profiles for the current authorized user. - $result = $service->userProfiles->listUserProfiles(); - foreach ($result['items'] as $userProfile) { - printf( - "User profile \"%s\" (ID: %d) found for account %d.\n", - $userProfile->getUserName(), - $userProfile->getProfileId(), - $userProfile->getAccountId() - ); - } - } -} - -if ($argc !== 2) { - printf("Usage: %s /path/to/client_secrets.json\n", $argv[0]); -} else { - $sample = new AuthenticateUsingUserAccount(); - $sample->run($argv[1]); -} diff --git a/php/v3.5/client_secrets.json b/php/v3.5/client_secrets.json deleted file mode 100755 index f29d5ac..0000000 --- a/php/v3.5/client_secrets.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "web": { - "client_id": "Enter Client ID", - "client_secret": "Enter Client Secret", - "redirect_uris": ["http://path/to/the/samples"] - } -} \ No newline at end of file diff --git a/php/v3.5/composer.json b/php/v3.5/composer.json deleted file mode 100755 index 801ab7f..0000000 --- a/php/v3.5/composer.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "require": { - "google/apiclient-services": "dev-master", - "google/apiclient": "^2.0", - "guzzlehttp/psr7": "^1.2" - } -} diff --git a/php/v3.5/composer.lock b/php/v3.5/composer.lock deleted file mode 100644 index 043c4ed..0000000 --- a/php/v3.5/composer.lock +++ /dev/null @@ -1,1064 +0,0 @@ -{ - "_readme": [ - "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", - "This file is @generated automatically" - ], - "content-hash": "93032904091df2a7d0d6c4d31011cc65", - "packages": [ - { - "name": "firebase/php-jwt", - "version": "v3.0.0", - "source": { - "type": "git", - "url": "https://github.com/firebase/php-jwt.git", - "reference": "fa8a06e96526eb7c0eeaa47e4f39be59d21f16e1" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/firebase/php-jwt/zipball/fa8a06e96526eb7c0eeaa47e4f39be59d21f16e1", - "reference": "fa8a06e96526eb7c0eeaa47e4f39be59d21f16e1", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "autoload": { - "psr-4": { - "Firebase\\JWT\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Neuman Vong", - "email": "neuman+pear@twilio.com", - "role": "Developer" - }, - { - "name": "Anant Narayanan", - "email": "anant@php.net", - "role": "Developer" - } - ], - "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", - "homepage": "https://github.com/firebase/php-jwt", - "support": { - "issues": "https://github.com/firebase/php-jwt/issues", - "source": "https://github.com/firebase/php-jwt/tree/v3.0.0" - }, - "time": "2015-07-22T18:31:08+00:00" - }, - { - "name": "google/apiclient", - "version": "v2.0.1", - "source": { - "type": "git", - "url": "https://github.com/googleapis/google-api-php-client.git", - "reference": "984f6a96297242e901bde518489374a9dec209df" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-api-php-client/zipball/984f6a96297242e901bde518489374a9dec209df", - "reference": "984f6a96297242e901bde518489374a9dec209df", - "shasum": "" - }, - "require": { - "firebase/php-jwt": "~2.0|~3.0", - "google/apiclient-services": "*@dev", - "google/auth": "0.9", - "guzzlehttp/guzzle": "~5.2|~6.0", - "guzzlehttp/psr7": "^1.2", - "monolog/monolog": "^1.17", - "php": ">=5.4", - "phpseclib/phpseclib": "~2.0" - }, - "require-dev": { - "phpunit/phpunit": "~4", - "squizlabs/php_codesniffer": "~2.3", - "symfony/css-selector": "~2.1", - "symfony/dom-crawler": "~2.1", - "tedivm/stash": "^0.14.1" - }, - "suggest": { - "tedivm/stash": "For caching certs and tokens (using Google_Client::setCache)" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.x-dev" - } - }, - "autoload": { - "psr-0": { - "Google_": "src/" - }, - "classmap": [ - "src/Google/Service/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "Apache-2.0" - ], - "description": "Client library for Google APIs", - "homepage": "http://developers.google.com/api-client-library/php", - "keywords": [ - "google" - ], - "support": { - "issues": "https://github.com/googleapis/google-api-php-client/issues", - "source": "https://github.com/googleapis/google-api-php-client/tree/v2.0.1" - }, - "time": "2016-06-24T16:44:42+00:00" - }, - { - "name": "google/apiclient-services", - "version": "dev-master", - "source": { - "type": "git", - "url": "https://github.com/googleapis/google-api-php-client-services.git", - "reference": "db74d52e4be7116cfe1049c619efef462a7a8533" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/db74d52e4be7116cfe1049c619efef462a7a8533", - "reference": "db74d52e4be7116cfe1049c619efef462a7a8533", - "shasum": "" - }, - "require": { - "php": ">=5.4" - }, - "require-dev": { - "phpunit/phpunit": "^4.8|^5" - }, - "default-branch": true, - "type": "library", - "autoload": { - "psr-0": { - "Google_Service_": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "Apache-2.0" - ], - "description": "Client library for Google APIs", - "homepage": "http://developers.google.com/api-client-library/php", - "keywords": [ - "google" - ], - "support": { - "issues": "https://github.com/googleapis/google-api-php-client-services/issues", - "source": "https://github.com/googleapis/google-api-php-client-services/tree/master" - }, - "time": "2021-06-02T15:32:04+00:00" - }, - { - "name": "google/auth", - "version": "v0.9", - "source": { - "type": "git", - "url": "https://github.com/googleapis/google-auth-library-php.git", - "reference": "47c3c6bece495e58381a21fed13a735bd23a51cc" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/47c3c6bece495e58381a21fed13a735bd23a51cc", - "reference": "47c3c6bece495e58381a21fed13a735bd23a51cc", - "shasum": "" - }, - "require": { - "firebase/php-jwt": "~2.0|~3.0", - "guzzlehttp/guzzle": "~5.3|~6.0", - "guzzlehttp/psr7": "~1.2", - "php": ">=5.4", - "psr/cache": "^1.0", - "psr/http-message": "^1.0" - }, - "require-dev": { - "friendsofphp/php-cs-fixer": "^1.11", - "phpunit/phpunit": "3.7.*" - }, - "type": "library", - "autoload": { - "classmap": [ - "src/" - ], - "psr-4": { - "Google\\Auth\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "Apache-2.0" - ], - "description": "Google Auth Library for PHP", - "homepage": "http://github.com/google/google-auth-library-php", - "keywords": [ - "Authentication", - "google", - "oauth2" - ], - "support": { - "issues": "https://github.com/googleapis/google-auth-library-php/issues", - "source": "https://github.com/googleapis/google-auth-library-php/tree/v0.9" - }, - "time": "2016-06-01T22:07:52+00:00" - }, - { - "name": "guzzlehttp/guzzle", - "version": "6.5.5", - "source": { - "type": "git", - "url": "https://github.com/guzzle/guzzle.git", - "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle/zipball/9d4290de1cfd701f38099ef7e183b64b4b7b0c5e", - "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e", - "shasum": "" - }, - "require": { - "ext-json": "*", - "guzzlehttp/promises": "^1.0", - "guzzlehttp/psr7": "^1.6.1", - "php": ">=5.5", - "symfony/polyfill-intl-idn": "^1.17.0" - }, - "require-dev": { - "ext-curl": "*", - "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0", - "psr/log": "^1.1" - }, - "suggest": { - "psr/log": "Required for using the Log middleware" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "6.5-dev" - } - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\": "src/" - }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "description": "Guzzle is a PHP HTTP client library", - "homepage": "http://guzzlephp.org/", - "keywords": [ - "client", - "curl", - "framework", - "http", - "http client", - "rest", - "web service" - ], - "support": { - "issues": "https://github.com/guzzle/guzzle/issues", - "source": "https://github.com/guzzle/guzzle/tree/6.5" - }, - "time": "2020-06-16T21:01:06+00:00" - }, - { - "name": "guzzlehttp/promises", - "version": "1.4.1", - "source": { - "type": "git", - "url": "https://github.com/guzzle/promises.git", - "reference": "8e7d04f1f6450fef59366c399cfad4b9383aa30d" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/promises/zipball/8e7d04f1f6450fef59366c399cfad4b9383aa30d", - "reference": "8e7d04f1f6450fef59366c399cfad4b9383aa30d", - "shasum": "" - }, - "require": { - "php": ">=5.5" - }, - "require-dev": { - "symfony/phpunit-bridge": "^4.4 || ^5.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.4-dev" - } - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\Promise\\": "src/" - }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "description": "Guzzle promises library", - "keywords": [ - "promise" - ], - "support": { - "issues": "https://github.com/guzzle/promises/issues", - "source": "https://github.com/guzzle/promises/tree/1.4.1" - }, - "time": "2021-03-07T09:25:29+00:00" - }, - { - "name": "guzzlehttp/psr7", - "version": "1.8.2", - "source": { - "type": "git", - "url": "https://github.com/guzzle/psr7.git", - "reference": "dc960a912984efb74d0a90222870c72c87f10c91" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/dc960a912984efb74d0a90222870c72c87f10c91", - "reference": "dc960a912984efb74d0a90222870c72c87f10c91", - "shasum": "" - }, - "require": { - "php": ">=5.4.0", - "psr/http-message": "~1.0", - "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" - }, - "provide": { - "psr/http-message-implementation": "1.0" - }, - "require-dev": { - "ext-zlib": "*", - "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.10" - }, - "suggest": { - "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.7-dev" - } - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\Psr7\\": "src/" - }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - }, - { - "name": "Tobias Schultze", - "homepage": "https://github.com/Tobion" - } - ], - "description": "PSR-7 message implementation that also provides common utility methods", - "keywords": [ - "http", - "message", - "psr-7", - "request", - "response", - "stream", - "uri", - "url" - ], - "support": { - "issues": "https://github.com/guzzle/psr7/issues", - "source": "https://github.com/guzzle/psr7/tree/1.8.2" - }, - "time": "2021-04-26T09:17:50+00:00" - }, - { - "name": "monolog/monolog", - "version": "1.26.1", - "source": { - "type": "git", - "url": "https://github.com/Seldaek/monolog.git", - "reference": "c6b00f05152ae2c9b04a448f99c7590beb6042f5" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/c6b00f05152ae2c9b04a448f99c7590beb6042f5", - "reference": "c6b00f05152ae2c9b04a448f99c7590beb6042f5", - "shasum": "" - }, - "require": { - "php": ">=5.3.0", - "psr/log": "~1.0" - }, - "provide": { - "psr/log-implementation": "1.0.0" - }, - "require-dev": { - "aws/aws-sdk-php": "^2.4.9 || ^3.0", - "doctrine/couchdb": "~1.0@dev", - "graylog2/gelf-php": "~1.0", - "php-amqplib/php-amqplib": "~2.4", - "php-console/php-console": "^3.1.3", - "phpstan/phpstan": "^0.12.59", - "phpunit/phpunit": "~4.5", - "ruflin/elastica": ">=0.90 <3.0", - "sentry/sentry": "^0.13", - "swiftmailer/swiftmailer": "^5.3|^6.0" - }, - "suggest": { - "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", - "doctrine/couchdb": "Allow sending log messages to a CouchDB server", - "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", - "ext-mongo": "Allow sending log messages to a MongoDB server", - "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", - "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", - "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", - "php-console/php-console": "Allow sending log messages to Google Chrome", - "rollbar/rollbar": "Allow sending log messages to Rollbar", - "ruflin/elastica": "Allow sending log messages to an Elastic Search server", - "sentry/sentry": "Allow sending log messages to a Sentry server" - }, - "type": "library", - "autoload": { - "psr-4": { - "Monolog\\": "src/Monolog" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jordi Boggiano", - "email": "j.boggiano@seld.be", - "homepage": "http://seld.be" - } - ], - "description": "Sends your logs to files, sockets, inboxes, databases and various web services", - "homepage": "http://github.com/Seldaek/monolog", - "keywords": [ - "log", - "logging", - "psr-3" - ], - "support": { - "issues": "https://github.com/Seldaek/monolog/issues", - "source": "https://github.com/Seldaek/monolog/tree/1.26.1" - }, - "funding": [ - { - "url": "https://github.com/Seldaek", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/monolog/monolog", - "type": "tidelift" - } - ], - "time": "2021-05-28T08:32:12+00:00" - }, - { - "name": "phpseclib/phpseclib", - "version": "2.0.31", - "source": { - "type": "git", - "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "233a920cb38636a43b18d428f9a8db1f0a1a08f4" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/233a920cb38636a43b18d428f9a8db1f0a1a08f4", - "reference": "233a920cb38636a43b18d428f9a8db1f0a1a08f4", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "require-dev": { - "phing/phing": "~2.7", - "phpunit/phpunit": "^4.8.35|^5.7|^6.0|^9.4", - "squizlabs/php_codesniffer": "~2.0" - }, - "suggest": { - "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", - "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", - "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", - "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." - }, - "type": "library", - "autoload": { - "files": [ - "phpseclib/bootstrap.php" - ], - "psr-4": { - "phpseclib\\": "phpseclib/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jim Wigginton", - "email": "terrafrost@php.net", - "role": "Lead Developer" - }, - { - "name": "Patrick Monnerat", - "email": "pm@datasphere.ch", - "role": "Developer" - }, - { - "name": "Andreas Fischer", - "email": "bantu@phpbb.com", - "role": "Developer" - }, - { - "name": "Hans-Jürgen Petrich", - "email": "petrich@tronic-media.com", - "role": "Developer" - }, - { - "name": "Graham Campbell", - "email": "graham@alt-three.com", - "role": "Developer" - } - ], - "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", - "homepage": "http://phpseclib.sourceforge.net", - "keywords": [ - "BigInteger", - "aes", - "asn.1", - "asn1", - "blowfish", - "crypto", - "cryptography", - "encryption", - "rsa", - "security", - "sftp", - "signature", - "signing", - "ssh", - "twofish", - "x.509", - "x509" - ], - "support": { - "issues": "https://github.com/phpseclib/phpseclib/issues", - "source": "https://github.com/phpseclib/phpseclib/tree/2.0.31" - }, - "funding": [ - { - "url": "https://github.com/terrafrost", - "type": "github" - }, - { - "url": "https://www.patreon.com/phpseclib", - "type": "patreon" - }, - { - "url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib", - "type": "tidelift" - } - ], - "time": "2021-04-06T13:56:45+00:00" - }, - { - "name": "psr/cache", - "version": "1.0.1", - "source": { - "type": "git", - "url": "https://github.com/php-fig/cache.git", - "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8", - "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Cache\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for caching libraries", - "keywords": [ - "cache", - "psr", - "psr-6" - ], - "support": { - "source": "https://github.com/php-fig/cache/tree/master" - }, - "time": "2016-08-06T20:24:11+00:00" - }, - { - "name": "psr/http-message", - "version": "1.0.1", - "source": { - "type": "git", - "url": "https://github.com/php-fig/http-message.git", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Http\\Message\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for HTTP messages", - "homepage": "https://github.com/php-fig/http-message", - "keywords": [ - "http", - "http-message", - "psr", - "psr-7", - "request", - "response" - ], - "support": { - "source": "https://github.com/php-fig/http-message/tree/master" - }, - "time": "2016-08-06T14:39:51+00:00" - }, - { - "name": "psr/log", - "version": "1.1.4", - "source": { - "type": "git", - "url": "https://github.com/php-fig/log.git", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.1.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Log\\": "Psr/Log/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "https://www.php-fig.org/" - } - ], - "description": "Common interface for logging libraries", - "homepage": "https://github.com/php-fig/log", - "keywords": [ - "log", - "psr", - "psr-3" - ], - "support": { - "source": "https://github.com/php-fig/log/tree/1.1.4" - }, - "time": "2021-05-03T11:20:27+00:00" - }, - { - "name": "ralouphie/getallheaders", - "version": "3.0.3", - "source": { - "type": "git", - "url": "https://github.com/ralouphie/getallheaders.git", - "reference": "120b605dfeb996808c31b6477290a714d356e822" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", - "reference": "120b605dfeb996808c31b6477290a714d356e822", - "shasum": "" - }, - "require": { - "php": ">=5.6" - }, - "require-dev": { - "php-coveralls/php-coveralls": "^2.1", - "phpunit/phpunit": "^5 || ^6.5" - }, - "type": "library", - "autoload": { - "files": [ - "src/getallheaders.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Ralph Khattar", - "email": "ralph.khattar@gmail.com" - } - ], - "description": "A polyfill for getallheaders.", - "support": { - "issues": "https://github.com/ralouphie/getallheaders/issues", - "source": "https://github.com/ralouphie/getallheaders/tree/develop" - }, - "time": "2019-03-08T08:55:37+00:00" - }, - { - "name": "symfony/polyfill-intl-idn", - "version": "v1.23.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-intl-idn.git", - "reference": "65bd267525e82759e7d8c4e8ceea44f398838e65" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/65bd267525e82759e7d8c4e8ceea44f398838e65", - "reference": "65bd267525e82759e7d8c4e8ceea44f398838e65", - "shasum": "" - }, - "require": { - "php": ">=7.1", - "symfony/polyfill-intl-normalizer": "^1.10", - "symfony/polyfill-php72": "^1.10" - }, - "suggest": { - "ext-intl": "For best performance" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Intl\\Idn\\": "" - }, - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Laurent Bassin", - "email": "laurent@bassin.info" - }, - { - "name": "Trevor Rowbotham", - "email": "trevor.rowbotham@pm.me" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "idn", - "intl", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.23.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2021-05-27T09:27:20+00:00" - }, - { - "name": "symfony/polyfill-intl-normalizer", - "version": "v1.23.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-intl-normalizer.git", - "reference": "8590a5f561694770bdcd3f9b5c69dde6945028e8" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/8590a5f561694770bdcd3f9b5c69dde6945028e8", - "reference": "8590a5f561694770bdcd3f9b5c69dde6945028e8", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "suggest": { - "ext-intl": "For best performance" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Intl\\Normalizer\\": "" - }, - "files": [ - "bootstrap.php" - ], - "classmap": [ - "Resources/stubs" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for intl's Normalizer class and related functions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "intl", - "normalizer", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.23.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2021-02-19T12:13:01+00:00" - }, - { - "name": "symfony/polyfill-php72", - "version": "v1.23.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php72.git", - "reference": "9a142215a36a3888e30d0a9eeea9766764e96976" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/9a142215a36a3888e30d0a9eeea9766764e96976", - "reference": "9a142215a36a3888e30d0a9eeea9766764e96976", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Php72\\": "" - }, - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-php72/tree/v1.23.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2021-05-27T09:17:38+00:00" - } - ], - "packages-dev": [], - "aliases": [], - "minimum-stability": "stable", - "stability-flags": { - "google/apiclient-services": 20 - }, - "prefer-stable": false, - "prefer-lowest": false, - "platform": [], - "platform-dev": [], - "plugin-api-version": "2.0.0" -} diff --git a/php/v3.5/examples/Ads/CreateRotationGroup.php b/php/v3.5/examples/Ads/CreateRotationGroup.php deleted file mode 100755 index 7c44556..0000000 --- a/php/v3.5/examples/Ads/CreateRotationGroup.php +++ /dev/null @@ -1,140 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'creative_id', - 'display' => 'Creative ID', - 'required' => true], - ['name' => 'placement_id', - 'display' => 'Placement ID', - 'required' => true], - ['name' => 'ad_name', - 'display' => 'Ad Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating rotation group ad with name "%s" for placement ID' - . ' %s

', - $values['ad_name'], - $values['placement_id'] - ); - - // Retrieve the campaign. - $campaign = $this->service->campaigns->get( - $values['user_profile_id'], - $values['campaign_id'] - ); - - // Create a click-through URL. - $url = new Google_Service_Dfareporting_ClickThroughUrl(); - $url->setDefaultLandingPage(true); - - // Create a creative assignment. - $creativeAssignment = - new Google_Service_Dfareporting_CreativeAssignment(); - $creativeAssignment->setActive(true); - $creativeAssignment->setCreativeId($values['creative_id']); - $creativeAssignment->setClickThroughUrl($url); - - // Create a placement assignment. - $placementAssignment = - new Google_Service_Dfareporting_PlacementAssignment(); - $placementAssignment->setActive(true); - $placementAssignment->setPlacementId($values['placement_id']); - - // Create a creative rotation. - $creativeRotation = new Google_Service_Dfareporting_CreativeRotation(); - $creativeRotation->setCreativeAssignments([$creativeAssignment]); - - // Create a delivery schedule. - $deliverySchedule = new Google_Service_Dfareporting_DeliverySchedule(); - $deliverySchedule->setImpressionRatio(1); - $deliverySchedule->SetPriority('AD_PRIORITY_01'); - - $startDate = new DateTime('today'); - $endDate = new DateTime($campaign->getEndDate()); - - // Create a rotation group. - $ad = new Google_Service_Dfareporting_Ad(); - $ad->setActive(true); - $ad->setCampaignId($values['campaign_id']); - $ad->setCreativeRotation($creativeRotation); - $ad->setDeliverySchedule($deliverySchedule); - $ad->setStartTime($startDate->format('Y-m-d') . 'T23:59:59Z'); - $ad->setEndTime($endDate->format('Y-m-d') . 'T00:00:00Z'); - $ad->setName($values['ad_name']); - $ad->setPlacementAssignments([$placementAssignment]); - $ad->setType('AD_SERVING_STANDARD_AD'); - - $result = $this->service->ads->insert($values['user_profile_id'], $ad); - - $this->printResultsTable('Rotation group ad created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Rotation Group Ad'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Ad ID', - 'name' => 'Ad Name']; - } -} diff --git a/php/v3.5/examples/Ads/GetAds.php b/php/v3.5/examples/Ads/GetAds.php deleted file mode 100755 index e62e6e3..0000000 --- a/php/v3.5/examples/Ads/GetAds.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all ads

'; - - $this->printResultsTableHeader('Ads'); - - $response = null; - $pageToken = null; - - do { - // Create and execute the ads list request. - $response = $this->service->ads->listAds( - $values['user_profile_id'], - ['active' => true, 'pageToken' => $pageToken] - ); - - foreach ($response->getAds() as $ads) { - $this->printResultsTableRow($ads); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getAds()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Ads'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Ad ID', - 'name' => 'Ad Name', - 'advertiserId' => 'Associated Advertiser ID']; - } -} diff --git a/php/v3.5/examples/Advertisers/AssignAdvertisersToAdvertiserGroup.php b/php/v3.5/examples/Advertisers/AssignAdvertisersToAdvertiserGroup.php deleted file mode 100755 index b78c16b..0000000 --- a/php/v3.5/examples/Advertisers/AssignAdvertisersToAdvertiserGroup.php +++ /dev/null @@ -1,94 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'advertiser_group_id', - 'display' => 'Advertiser Group ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Assigning advertiser ID %s to advertiser group ID %s

', - $values['advertiser_id'], - $values['advertiser_group_id'] - ); - - $advertiser = new Google_Service_Dfareporting_Advertiser(); - $advertiser->setAdvertiserGroupId($values['advertiser_group_id']); - - $result = $this->service->advertisers->patch( - $values['user_profile_id'], - $values['advertiser_id'], - $advertiser - ); - - $this->printResultsTable('Advertiser', [$result]); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Assign Advertiser To Advertiser Group'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser ID', - 'name' => 'Advertiser Name', - 'advertiserGroupId' => 'Advertiser Group ID']; - } -} diff --git a/php/v3.5/examples/Advertisers/CreateAdvertiser.php b/php/v3.5/examples/Advertisers/CreateAdvertiser.php deleted file mode 100755 index f41447f..0000000 --- a/php/v3.5/examples/Advertisers/CreateAdvertiser.php +++ /dev/null @@ -1,87 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_name', - 'display' => 'Advertiser Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating advertiser with name "%s"

', - $values['advertiser_name'] - ); - - $advertiser = new Google_Service_Dfareporting_Advertiser(); - $advertiser->setName($values['advertiser_name']); - $advertiser->setStatus('APPROVED'); - - $result = $this->service->advertisers->insert( - $values['user_profile_id'], - $advertiser - ); - - $this->printResultsTable('Advertiser created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Advertiser'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser ID', - 'name' => 'Advertiser Name']; - } -} diff --git a/php/v3.5/examples/Advertisers/CreateAdvertiserGroup.php b/php/v3.5/examples/Advertisers/CreateAdvertiserGroup.php deleted file mode 100755 index c984cae..0000000 --- a/php/v3.5/examples/Advertisers/CreateAdvertiserGroup.php +++ /dev/null @@ -1,87 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_group_name', - 'display' => 'Advertiser Group Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating advertiser group with name "%s"

', - $values['advertiser_group_name'] - ); - - $advertiser = new Google_Service_Dfareporting_AdvertiserGroup(); - $advertiser->setName($values['advertiser_group_name']); - - - $result = $this->service->advertiserGroups->insert( - $values['user_profile_id'], - $advertiser - ); - - $this->printResultsTable('Advertiser group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Advertiser Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Group ID', - 'name' => 'Advertiser Group Name']; - } -} diff --git a/php/v3.5/examples/Advertisers/CreateAdvertiserLandingPage.php b/php/v3.5/examples/Advertisers/CreateAdvertiserLandingPage.php deleted file mode 100755 index bef2442..0000000 --- a/php/v3.5/examples/Advertisers/CreateAdvertiserLandingPage.php +++ /dev/null @@ -1,95 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'landing_page_name', - 'display' => 'Landing Page Name', - 'required' => true], - ['name' => 'landing_page_url', - 'display' => 'Landing Page URL', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating advertiser landing page for advertiser %d

', - $values['advertiser_id'] - ); - - $landingPage = new Google_Service_Dfareporting_LandingPage(); - $landingPage->setAdvertiserId($values['advertiser_id']); - $landingPage->setArchived(false); - $landingPage->setName($values['landing_page_name']); - $landingPage->setUrl($values['landing_page_url']); - - $result = $this->service->advertiserLandingPages->insert( - $values['user_profile_id'], - $landingPage - ); - - $this->printResultsTable('Advertiser landing page created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Advertiser Landing Page'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Landing Page ID', - 'name' => 'Advertiser Landing Page Name', - 'url' => 'Advertiser Landing Page URL']; - } -} diff --git a/php/v3.5/examples/Advertisers/GetAdvertiserGroups.php b/php/v3.5/examples/Advertisers/GetAdvertiserGroups.php deleted file mode 100755 index 714c04c..0000000 --- a/php/v3.5/examples/Advertisers/GetAdvertiserGroups.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all advertiser groups

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Advertiser groups'); - - do { - // Create and execute the advertiser groups list request. - $response = $this->service->advertiserGroups->listAdvertiserGroups( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getAdvertiserGroups() as $group) { - $this->printResultsTableRow($group); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getAdvertiserGroups()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Advertiser Groups'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Group ID', - 'name' => 'Advertiser Group Name']; - } -} diff --git a/php/v3.5/examples/Advertisers/GetAdvertiserLandingPages.php b/php/v3.5/examples/Advertisers/GetAdvertiserLandingPages.php deleted file mode 100755 index f986b58..0000000 --- a/php/v3.5/examples/Advertisers/GetAdvertiserLandingPages.php +++ /dev/null @@ -1,101 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all landing pages for advertiser %d

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Advertiser landing pages'); - - do { - // Create and execute the advertiser landing page list request. - $response = - $this->service->advertiserLandingPages->listAdvertiserLandingPages( - $values['user_profile_id'], - ['advertiserIds' => [$values['advertiser_id']], - 'pageToken' => $pageToken] - ); - - foreach ($response->getLandingPages() as $landingPage) { - $this->printResultsTableRow($landingPage); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getLandingPages()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Advertiser Landing Pages'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser Landing Page ID', - 'name' => 'Advertiser Landing Page Name', - 'url' => 'Advertiser Landing Page URL']; - } -} diff --git a/php/v3.5/examples/Advertisers/GetAdvertisers.php b/php/v3.5/examples/Advertisers/GetAdvertisers.php deleted file mode 100755 index 0a31931..0000000 --- a/php/v3.5/examples/Advertisers/GetAdvertisers.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all advertisers

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Advertisers'); - - do { - // Create and execute the advertisers list request. - $response = $this->service->advertisers->listAdvertisers( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getAdvertisers() as $advertiser) { - $this->printResultsTableRow($advertiser); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getAdvertisers()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Advertisers'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Advertiser ID', - 'name' => 'Advertiser Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.5/examples/BaseExample.php b/php/v3.5/examples/BaseExample.php deleted file mode 100755 index 94daa42..0000000 --- a/php/v3.5/examples/BaseExample.php +++ /dev/null @@ -1,277 +0,0 @@ -service = $service; - $this->headers = $this->getResultsTableHeaders(); - } - - /** - * Contains the logic of the example. - */ - abstract protected function run(); - - /** - * Executes the example, checks if the examples requires parameters and - * request them before invoking run. - */ - public function execute() - { - if (count($this->getInputParameters())) { - if ($this->isSubmitComplete()) { - $this->formValues = $this->getFormValues(); - $this->run(); - } else { - $this->renderInputForm(); - } - } else { - $this->run(); - } - } - - /** - * Returns a display name for the example. - * @return string - */ - abstract public function getName(); - - /** - * Returns the list of input parameters of the example. - * To be overridden by examples that require parameters. - * @return array - */ - protected function getInputParameters() - { - return []; - } - - /** - * Returns the list of headers to be shown in the results table. - * To be overridden by examples that require table headers. - * @return array - */ - protected function getResultsTableHeaders() - { - return []; - } - - /** - * Renders an input form to capture the example parameters. - */ - protected function renderInputForm() - { - $parameters = $this->getInputParameters(); - if (count($parameters)) { - printf('

Enter %s parameters

', $this->getName()); - print '
'; - foreach ($parameters as $parameter) { - $name = $parameter['name']; - $display = $parameter['display']; - - if (isset($_POST[$name])) { - $currentValue = $_POST[$name]; - } else { - $currentValue = ''; - } - - // If this is a file parameter, generate a file input element - if ($parameter['file']) { - $inputType = ' type="file"'; - } - - printf( - '%s: ', - $display, - $name, - $currentValue, - $inputType - ); - - if ($parameter['required']) { - print '*'; - } - - print '
'; - } - print '
*required
'; - print ''; - print '
'; - } - - $this->flush(); - } - - /** - * Checks if the form has been submitted and all required parameters are - * set. - * @return bool - */ - protected function isSubmitComplete() - { - if (!isset($_POST['submit'])) { - return false; - } - - foreach ($this->getInputParameters() as $parameter) { - if ($parameter['required']) { - if ($parameter['file']) { - return !empty($_FILES[$parameter['name']]); - } else { - return !empty($_POST[$parameter['name']]); - } - } - } - - return true; - } - - /** - * Retrieves the submitted form values. - * @return array - */ - protected function getFormValues() - { - $input = []; - - foreach ($this->getInputParameters() as $parameter) { - if ($parameter['file'] && isset($_FILES[$parameter['name']])) { - $input[$parameter['name']] = $_FILES[$parameter['name']]; - } elseif (isset($_POST[$parameter['name']])) { - $input[$parameter['name']] = $_POST[$parameter['name']]; - } - } - - return $input; - } - - /** - * Prints out the header for the results table. - * @param string $title - * A friendly name for the results table - */ - protected function printResultsTableHeader($title) - { - printf('

%s

', $title); - print ''; - - foreach ($this->headers as $name => $value) { - printf('', $value); - } - - print ''; - $this->flush(); - } - - /** - * Prints out a row of data for the results table. - * @param array $row - * Values representing a single row in the results table - */ - protected function printResultsTableRow($row) - { - print ''; - - foreach ($this->headers as $name => $value) { - print ''; - } - - print ''; - $this->flush(); - } - - /** - * Prints out a "No results" row for the results table. - */ - protected function printNoResultsTableRow() - { - print ''; - printf( - '', - count($this->headers) - ); - print ''; - $this->flush(); - } - - /** - * Prints out the footer for the results table. - */ - protected function printResultsTableFooter() - { - print '
%s
'; - print_r($row[$name]); - print '
No results.

'; - $this->flush(); - } - - /** - * Convenience method to print an entire results table at once. - * @param string $title - * A friendly name for the results table - * @param array $rows - * Values representing multiple rows in the results table - */ - protected function printResultsTable($title, $rows) - { - $this->printResultsTableHeader($title); - - if (empty($rows)) { - $this->printNoResultsTableRow(); - } else { - foreach ($rows as $row) { - $this->printResultsTableRow($row); - } - } - - $this->printResultsTableFooter(); - } - - /** - * Flushes the contents of the output buffer. - */ - protected function flush() - { - ob_flush(); - flush(); - } -} diff --git a/php/v3.5/examples/Campaigns/CreateCampaign.php b/php/v3.5/examples/Campaigns/CreateCampaign.php deleted file mode 100755 index 5fa4c7e..0000000 --- a/php/v3.5/examples/Campaigns/CreateCampaign.php +++ /dev/null @@ -1,99 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'campaign_name', - 'display' => 'Campaign Name', - 'required' => true], - ['name' => 'default_landing_page_id', - 'display' => 'Default Landing Page ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating campaign with name "%s"

', - $values['campaign_name'] - ); - - $startDate = new DateTime('today'); - $endDate = new DateTime('+1 month'); - - $campaign = new Google_Service_Dfareporting_Campaign(); - $campaign->setAdvertiserId($values['advertiser_id']); - $campaign->setDefaultLandingPageId($values['default_landing_page_id']); - $campaign->setName($values['campaign_name']); - $campaign->setStartDate($startDate->format('Y-m-d')); - $campaign->setEndDate($endDate->format('Y-m-d')); - - $result = $this->service->campaigns->insert( - $values['user_profile_id'], - $campaign - ); - - $this->printResultsTable('Campaign created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Campaign'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Campaign ID', - 'name' => 'Campaign Name']; - } -} diff --git a/php/v3.5/examples/Campaigns/CreateCampaignEventTag.php b/php/v3.5/examples/Campaigns/CreateCampaignEventTag.php deleted file mode 100755 index ebf57a3..0000000 --- a/php/v3.5/examples/Campaigns/CreateCampaignEventTag.php +++ /dev/null @@ -1,95 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'event_tag_name', - 'display' => 'Event Tag Name', - 'required' => true], - ['name' => 'event_tag_url', - 'display' => 'Event Tag URL', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating campaign event tag with name "%s"

', - $values['event_tag_name'] - ); - - $eventTag = new Google_Service_Dfareporting_EventTag(); - $eventTag->setCampaignId($values['campaign_id']); - $eventTag->setName($values['event_tag_name']); - $eventTag->setStatus('ENABLED'); - $eventTag->setType('CLICK_THROUGH_EVENT_TAG'); - $eventTag->setUrl($values['event_tag_url']); - - $result = $this->service->eventTags->insert( - $values['user_profile_id'], - $eventTag - ); - - $this->printResultsTable('Campaign event tag created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Campaign Event Tag'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Event Tag ID', - 'name' => 'Event Tag Name']; - } -} diff --git a/php/v3.5/examples/Campaigns/GetCampaigns.php b/php/v3.5/examples/Campaigns/GetCampaigns.php deleted file mode 100755 index 12ff8b9..0000000 --- a/php/v3.5/examples/Campaigns/GetCampaigns.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all campaigns

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Campaigns'); - - do { - // Create and execute the ads list request. - $response = $this->service->campaigns->listCampaigns( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCampaigns() as $campaigns) { - $this->printResultsTableRow($campaigns); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCampaigns()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Campaigns'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Campaign ID', - 'name' => 'Campaign Name']; - } -} diff --git a/php/v3.5/examples/Conversions/InsertOfflineMobileConversion.php b/php/v3.5/examples/Conversions/InsertOfflineMobileConversion.php deleted file mode 100755 index a75882c..0000000 --- a/php/v3.5/examples/Conversions/InsertOfflineMobileConversion.php +++ /dev/null @@ -1,110 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'mobile_device_id', - 'display' => 'Mobile Device ID', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Inserting offline conversion for mobile device ID "%s"

', - $values['mobile_device_id'] - ); - - $currentTimeInMicros = time() * 1000 * 1000; - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setMobileDeviceId($values['mobile_device_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($currentTimeInMicros); - $conversion->setTimestampMicros($currentTimeInMicros); - - $batch = new Google_Service_Dfareporting_ConversionsBatchInsertRequest(); - $batch->setConversions([$conversion]); - - $result = $this->service->conversions->batchinsert( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully inserted conversion for mobile device ID %s.', - $values['mobile_device_id'] - ); - } else { - printf( - 'Error(s) inserting conversion for mobile device ID %s:

', - $values['mobile_device_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Insert Offline Mobile Conversion'; - } -} diff --git a/php/v3.5/examples/Conversions/InsertOfflineUserConversion.php b/php/v3.5/examples/Conversions/InsertOfflineUserConversion.php deleted file mode 100755 index 7893824..0000000 --- a/php/v3.5/examples/Conversions/InsertOfflineUserConversion.php +++ /dev/null @@ -1,125 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'encrypted_user_id', - 'display' => 'Encrypted User ID', - 'required' => true], - ['name' => 'encryption_entity_id', - 'display' => 'Encryption Entity ID', - 'required' => true], - ['name' => 'encryption_entity_type', - 'display' => 'Encryption Entity Type', - 'required' => true], - ['name' => 'encryption_source', - 'display' => 'Encryption Source', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Inserting offline conversion for encrypted user ID "%s"

', - $values['encrypted_user_id'] - ); - - $currentTimeInMicros = time() * 1000 * 1000; - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setEncryptedUserId($values['encrypted_user_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($currentTimeInMicros); - $conversion->setTimestampMicros($currentTimeInMicros); - - $encryptionInfo = new Google_Service_Dfareporting_EncryptionInfo(); - $encryptionInfo->setEncryptionEntityId($values['encryption_entity_id']); - $encryptionInfo->setEncryptionEntityType($values['encryption_entity_type']); - $encryptionInfo->setEncryptionSource($values['encryption_source']); - - $batch = new Google_Service_Dfareporting_ConversionsBatchInsertRequest(); - $batch->setConversions([$conversion]); - $batch->setEncryptionInfo($encryptionInfo); - - $result = $this->service->conversions->batchinsert( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully inserted conversion for encrypted user ID %s.', - $values['encrypted_user_id'] - ); - } else { - printf( - 'Error(s) inserting conversion for encrypted user ID %s:

', - $values['encrypted_user_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Insert Offline User Conversion'; - } -} diff --git a/php/v3.5/examples/Conversions/UpdateOfflineMobileConversion.php b/php/v3.5/examples/Conversions/UpdateOfflineMobileConversion.php deleted file mode 100755 index 587de8d..0000000 --- a/php/v3.5/examples/Conversions/UpdateOfflineMobileConversion.php +++ /dev/null @@ -1,127 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'mobile_device_id', - 'display' => 'Mobile Device ID', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true], - ['name' => 'ordinal', - 'display' => 'Ordinal', - 'required' => true], - ['name' => 'timestamp', - 'display' => 'Timestamp (microseconds)', - 'required' => true], - ['name' => 'new_quantity', - 'display' => 'New Quantity', - 'required' => true], - ['name' => 'new_value', - 'display' => 'New Value', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Updating offline conversion for mobile device ID "%s"

', - $values['mobile_device_id'] - ); - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - // Create a conversion object with values that identify the conversion to - // update. - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setMobileDeviceId($values['mobile_device_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($values['ordinal']); - $conversion->setTimestampMicros($values['timestamp']); - - // Set the fields to be updated. These fields are required; to preserve a - // value from the existing conversion, it must be copied over manually. - $conversion->setQuantity($values['new_quantity']); - $conversion->setValue($values['new_value']); - - $batch = new Google_Service_Dfareporting_ConversionsBatchUpdateRequest(); - $batch->setConversions([$conversion]); - - $result = $this->service->conversions->batchupdate( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully updated conversion for mobile device ID %s.', - $values['mobile_device_id'] - ); - } else { - printf( - 'Error(s) updating conversion for mobile device ID %s:

', - $values['mobile_device_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Update Offline Mobile Conversion'; - } -} diff --git a/php/v3.5/examples/Conversions/UpdateOfflineUserConversion.php b/php/v3.5/examples/Conversions/UpdateOfflineUserConversion.php deleted file mode 100755 index aa09117..0000000 --- a/php/v3.5/examples/Conversions/UpdateOfflineUserConversion.php +++ /dev/null @@ -1,142 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'encrypted_user_id', - 'display' => 'Encrypted User ID', - 'required' => true], - ['name' => 'encryption_entity_id', - 'display' => 'Encryption Entity ID', - 'required' => true], - ['name' => 'encryption_entity_type', - 'display' => 'Encryption Entity Type', - 'required' => true], - ['name' => 'encryption_source', - 'display' => 'Encryption Source', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true], - ['name' => 'ordinal', - 'display' => 'Ordinal', - 'required' => true], - ['name' => 'timestamp', - 'display' => 'Timestamp (microseconds)', - 'required' => true], - ['name' => 'new_quantity', - 'display' => 'New Quantity', - 'required' => true], - ['name' => 'new_value', - 'display' => 'New Value', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Updating offline conversion for encrypted user ID "%s"

', - $values['encrypted_user_id'] - ); - - // Find Floodlight configuration ID based on provided activity ID. - $activity = $this->service->floodlightActivities->get( - $values['user_profile_id'], - $values['floodlight_activity_id'] - ); - $floodlightConfigId = $activity->getFloodlightConfigurationId(); - - // Create a conversion object with values that identify the conversion to - // update. - $conversion = new Google_Service_Dfareporting_Conversion(); - $conversion->setEncryptedUserId($values['encrypted_user_id']); - $conversion->setFloodlightActivityId($values['floodlight_activity_id']); - $conversion->setFloodlightConfigurationId($floodlightConfigId); - $conversion->setOrdinal($values['ordinal']); - $conversion->setTimestampMicros($values['timestamp']); - - // Set the fields to be updated. These fields are required; to preserve a - // value from the existing conversion, it must be copied over manually. - $conversion->setQuantity($values['new_quantity']); - $conversion->setValue($values['new_value']); - - $encryptionInfo = new Google_Service_Dfareporting_EncryptionInfo(); - $encryptionInfo->setEncryptionEntityId($values['encryption_entity_id']); - $encryptionInfo->setEncryptionEntityType($values['encryption_entity_type']); - $encryptionInfo->setEncryptionSource($values['encryption_source']); - - $batch = new Google_Service_Dfareporting_ConversionsBatchUpdateRequest(); - $batch->setConversions([$conversion]); - $batch->setEncryptionInfo($encryptionInfo); - - $result = $this->service->conversions->batchupdate( - $values['user_profile_id'], - $batch - ); - - if (!$result->getHasFailures()) { - printf( - 'Successfully updated conversion for encrypted user ID %s.', - $values['encrypted_user_id'] - ); - } else { - printf( - 'Error(s) updating conversion for encrypted user ID %s:

', - $values['encrypted_user_id'] - ); - - $status = $result->getStatus()[0]; - foreach ($status->getErrors() as $error) { - printf('[%s] %s
', $error->getCode(), $error->getMessage()); - } - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Update Offline User Conversion'; - } -} diff --git a/php/v3.5/examples/CreativeAssetUtils.php b/php/v3.5/examples/CreativeAssetUtils.php deleted file mode 100755 index 4ee64bb..0000000 --- a/php/v3.5/examples/CreativeAssetUtils.php +++ /dev/null @@ -1,42 +0,0 @@ -setName($asset['name']); - $assetId->setType($type); - - $metadata = new Google_Service_Dfareporting_CreativeAssetMetadata(); - $metadata->setAssetIdentifier($assetId); - - $result = $service->creativeAssets->insert( - $userProfileId, - $advertiserId, - $metadata, - ['data' => file_get_contents($asset['tmp_name']), - 'mimeType' => $asset['type'], - 'uploadType' => 'multipart'] - ); - - return $result; -} diff --git a/php/v3.5/examples/Creatives/AssignCreativeToCampaign.php b/php/v3.5/examples/Creatives/AssignCreativeToCampaign.php deleted file mode 100755 index 320014a..0000000 --- a/php/v3.5/examples/Creatives/AssignCreativeToCampaign.php +++ /dev/null @@ -1,85 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'creative_id', - 'display' => 'Creative ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Assigning creative ID %s to campaign ID %s

', - $values['creative_id'], - $values['campaign_id'] - ); - - $association = - new Google_Service_Dfareporting_CampaignCreativeAssociation(); - $association->setCreativeId($values['creative_id']); - - $result = $this->service->campaignCreativeAssociations->insert( - $values['user_profile_id'], - $values['campaign_id'], - $association - ); - - printf( - 'Successfully associated creative ID %s with campaign ID %s.', - $result->getCreativeId(), - $values['campaign_id'] - ); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Assign Creative To Campaign'; - } -} diff --git a/php/v3.5/examples/Creatives/CreateCreativeField.php b/php/v3.5/examples/Creatives/CreateCreativeField.php deleted file mode 100755 index 58b222b..0000000 --- a/php/v3.5/examples/Creatives/CreateCreativeField.php +++ /dev/null @@ -1,90 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'field_name', - 'display' => 'Creative Field Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating creative field with name "%s"

', - $values['field_name'] - ); - - $field = new Google_Service_Dfareporting_CreativeField(); - $field->setAdvertiserId($values['advertiser_id']); - $field->setName($values['field_name']); - - $result = $this->service->creativeFields->insert( - $values['user_profile_id'], - $field - ); - - $this->printResultsTable('Creative field created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Creative Field'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field ID', - 'name' => 'Creative Field Name']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateCreativeFieldValue.php b/php/v3.5/examples/Creatives/CreateCreativeFieldValue.php deleted file mode 100755 index e454eb0..0000000 --- a/php/v3.5/examples/Creatives/CreateCreativeFieldValue.php +++ /dev/null @@ -1,90 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'creative_field_id', - 'display' => 'Creative Field ID', - 'required' => true], - ['name' => 'field_value', - 'display' => 'Creative Field Value', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating creative field value with value "%s"

', - $values['field_value'] - ); - - $fieldValue = new Google_Service_Dfareporting_CreativeFieldValue(); - $fieldValue->setValue($values['field_value']); - - $result = $this->service->creativeFieldValues->insert( - $values['user_profile_id'], - $values['creative_field_id'], - $fieldValue - ); - - $this->printResultsTable('Creative field value created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Creative Field Value'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field Value ID', - 'value' => 'Creative Field Value']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateCreativeGroup.php b/php/v3.5/examples/Creatives/CreateCreativeGroup.php deleted file mode 100755 index 74a41a4..0000000 --- a/php/v3.5/examples/Creatives/CreateCreativeGroup.php +++ /dev/null @@ -1,96 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'group_name', - 'display' => 'Creative Group Name', - 'required' => true], - ['name' => 'group_number', - 'display' => 'Creative Group Number (1-2)', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating creative group with name "%s"

', - $values['group_name'] - ); - - $group = new Google_Service_Dfareporting_CreativeGroup(); - $group->setAdvertiserId($values['advertiser_id']); - $group->setGroupNumber($values['group_number']); - $group->setName($values['group_name']); - - $result = $this->service->creativeGroups->insert( - $values['user_profile_id'], - $group - ); - - $this->printResultsTable('Creative group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Creative Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Group ID', - 'name' => 'Creative Group Name', - 'groupNumber' => 'Creative Group Number']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateDisplayImageGalleryCreative.php b/php/v3.5/examples/Creatives/CreateDisplayImageGalleryCreative.php deleted file mode 100755 index 9f76041..0000000 --- a/php/v3.5/examples/Creatives/CreateDisplayImageGalleryCreative.php +++ /dev/null @@ -1,151 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'image1_asset_file', - 'display' => 'First Image Asset File', - 'file' => true, - 'required' => true], - ['name' => 'image2_asset_file', - 'display' => 'Second Image Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating display image gallery creative from "%s" and "%s"

', - $values['image1_asset_file']['name'], - $values['image2_asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setAutoAdvanceImages(true); - $creative->setName('Test display image gallery creative'); - $creative->setType('DISPLAY_IMAGE_GALLERY'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the first image asset. - $image1 = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['image1_asset_file'], - 'HTML_IMAGE' - ); - - $image1Asset = new Google_Service_Dfareporting_CreativeAsset(); - $image1Asset->setAssetIdentifier($image1->getAssetIdentifier()); - $image1Asset->setRole('PRIMARY'); - - // Upload the second image asset. - $image2 = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['image2_asset_file'], - 'HTML_IMAGE' - ); - - $image2Asset = new Google_Service_Dfareporting_CreativeAsset(); - $image2Asset->setAssetIdentifier($image2->getAssetIdentifier()); - $image2Asset->setRole('PRIMARY'); - - // Add the creative assets. - $creative->setCreativeAssets([$image1Asset, $image2Asset]); - - // Add a click tag for the first image asset. - $clickTag1 = new Google_Service_Dfareporting_ClickTag(); - $clickTag1->setName($image1->getAssetIdentifier()->getName()); - $clickTag1->setEventName($image1->getAssetIdentifier()->getName()); - - // Add a click tag for the second image asset. - $clickTag2 = new Google_Service_Dfareporting_ClickTag(); - $clickTag2->setName($image2->getAssetIdentifier()->getName()); - $clickTag2->setEventName($image2->getAssetIdentifier()->getName()); - - $creative->setClickTags([$clickTag1, $clickTag2]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable( - 'Display image gallery creative created.', - [$result] - ); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Display Image Gallery Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateDisplayRedirectCreative.php b/php/v3.5/examples/Creatives/CreateDisplayRedirectCreative.php deleted file mode 100755 index 8e43514..0000000 --- a/php/v3.5/examples/Creatives/CreateDisplayRedirectCreative.php +++ /dev/null @@ -1,100 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'image_url', - 'display' => 'Image File URL', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating display redirect creative from image URL "%s"

', - $values['image_url'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test display redirect creative'); - $creative->setRedirectUrl($values['image_url']); - $creative->setType('DISPLAY_REDIRECT'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('Display redirect creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Display Redirect Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateHTML5DisplayCreative.php b/php/v3.5/examples/Creatives/CreateHTML5DisplayCreative.php deleted file mode 100755 index 566c761..0000000 --- a/php/v3.5/examples/Creatives/CreateHTML5DisplayCreative.php +++ /dev/null @@ -1,158 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'landing_page_id', - 'display' => 'Landing Page ID', - 'required' => true], - ['name' => 'html_asset_file', - 'display' => 'HTML5 Asset File', - 'file' => true, - 'required' => true], - ['name' => 'image_asset_file', - 'display' => 'Backup Image Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating HTML5 display creative from HTML5 asset "%s"

', - $values['html_asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setAutoAdvanceImages(true); - $creative->setName('Test HTML5 display creative'); - $creative->setType('DISPLAY'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the HTML5 asset. - $html = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['html_asset_file'], - 'HTML' - ); - - $htmlAsset = new Google_Service_Dfareporting_CreativeAsset(); - $htmlAsset->setAssetIdentifier($html->getAssetIdentifier()); - $htmlAsset->setRole('PRIMARY'); - - // Upload the backup image asset. - $image = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['image_asset_file'], - 'HTML_IMAGE' - ); - - $imageAsset = new Google_Service_Dfareporting_CreativeAsset(); - $imageAsset->setAssetIdentifier($image->getAssetIdentifier()); - $imageAsset->setRole('BACKUP_IMAGE'); - - // Add the creative assets. - $creative->setCreativeAssets([$htmlAsset, $imageAsset]); - - // Configure the default click-through URL. - $clickThroughUrl = - new Google_Service_Dfareporting_CreativeClickThroughUrl(); - $clickThroughUrl->setLandingPageId($values['landing_page_id']); - - // Configure the backup image. - $creative->setBackupImageClickThroughUrl($clickThroughUrl); - $creative->setBackupImageReportingLabel('backup'); - - $targetWindow = new Google_Service_Dfareporting_TargetWindow(); - $targetWindow->setTargetWindowOption('NEW_WINDOW'); - $creative->setBackupImageTargetWindow($targetWindow); - - // Add a click tag. - $clickTag = new Google_Service_Dfareporting_ClickTag(); - $clickTag->setName('clickTag'); - $clickTag->setEventName('exit'); - $clickTag->setClickThroughUrl($clickThroughUrl); - $creative->setClickTags([$clickTag]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('HTML5 display creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create HTML5 Display Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateImageDisplayCreative.php b/php/v3.5/examples/Creatives/CreateImageDisplayCreative.php deleted file mode 100755 index 9a2bac7..0000000 --- a/php/v3.5/examples/Creatives/CreateImageDisplayCreative.php +++ /dev/null @@ -1,117 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Image Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating image display creative from image asset "%s"

', - $values['asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test image display creative'); - $creative->setType('DISPLAY'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the image asset. - $image = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['asset_file'], - 'HTML_IMAGE' - ); - - $asset = new Google_Service_Dfareporting_CreativeAsset(); - $asset->setAssetIdentifier($image->getAssetIdentifier()); - $asset->setRole('PRIMARY'); - - // Add the creative asset. - $creative->setCreativeAssets([$asset]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('Image display creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Image Display Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateInstreamAudioCreative.php b/php/v3.5/examples/Creatives/CreateInstreamAudioCreative.php deleted file mode 100755 index e4545df..0000000 --- a/php/v3.5/examples/Creatives/CreateInstreamAudioCreative.php +++ /dev/null @@ -1,114 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Audio Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating in-stream audio creative from audio asset "%s"

', - $values['asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test in-stream audio creative'); - $creative->setType('INSTREAM_AUDIO'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the audio asset. - $audio = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['asset_file'], - 'AUDIO' - ); - - $asset = new Google_Service_Dfareporting_CreativeAsset(); - $asset->setAssetIdentifier($audio->getAssetIdentifier()); - $asset->setRole('PARENT_AUDIO'); - - // Add the creative asset. - $creative->setCreativeAssets([$asset]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('In-stream audio creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create In-stream Audio Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateInstreamVideoCreative.php b/php/v3.5/examples/Creatives/CreateInstreamVideoCreative.php deleted file mode 100755 index 3e27179..0000000 --- a/php/v3.5/examples/Creatives/CreateInstreamVideoCreative.php +++ /dev/null @@ -1,114 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Video Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating in-stream video creative from video asset "%s"

', - $values['asset_file']['name'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test in-stream video creative'); - $creative->setType('INSTREAM_VIDEO'); - - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $creative->setSize($size); - - // Upload the video asset. - $video = uploadAsset( - $this->service, - $values['user_profile_id'], - $values['advertiser_id'], - $values['asset_file'], - 'VIDEO' - ); - - $asset = new Google_Service_Dfareporting_CreativeAsset(); - $asset->setAssetIdentifier($video->getAssetIdentifier()); - $asset->setRole('PARENT_VIDEO'); - - // Add the creative asset. - $creative->setCreativeAssets([$asset]); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('In-stream video creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create In-stream Video Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.5/examples/Creatives/CreateTrackingCreative.php b/php/v3.5/examples/Creatives/CreateTrackingCreative.php deleted file mode 100755 index 63255a9..0000000 --- a/php/v3.5/examples/Creatives/CreateTrackingCreative.php +++ /dev/null @@ -1,88 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating tracking creative for advertiser ID %s

', - $values['advertiser_id'] - ); - - $creative = new Google_Service_Dfareporting_Creative(); - $creative->setAdvertiserId($values['advertiser_id']); - $creative->setName('Test tracking creative'); - $creative->setType('TRACKING_TEXT'); - - $result = $this->service->creatives->insert( - $values['user_profile_id'], - $creative - ); - - $this->printResultsTable('Tracking creative created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Tracking Creative'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative type']; - } -} diff --git a/php/v3.5/examples/Creatives/GetCreativeFieldValues.php b/php/v3.5/examples/Creatives/GetCreativeFieldValues.php deleted file mode 100755 index 3216daf..0000000 --- a/php/v3.5/examples/Creatives/GetCreativeFieldValues.php +++ /dev/null @@ -1,100 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'field_id', - 'display' => 'Creative Field ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all creative field values for creative field ID %s

', - $values['field_id'] - ); - - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creative Field Values'); - - do { - // Create and execute the creative field values list request. - $response = $this->service->creativeFieldValues->listCreativeFieldValues( - $values['user_profile_id'], - $values['field_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCreativeFieldValues() as $values) { - $this->printResultsTableRow($values); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreativeFieldValues()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creative Field Values'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field Value ID', - 'value' => 'Creative Field Value']; - } -} diff --git a/php/v3.5/examples/Creatives/GetCreativeFields.php b/php/v3.5/examples/Creatives/GetCreativeFields.php deleted file mode 100755 index c0580d5..0000000 --- a/php/v3.5/examples/Creatives/GetCreativeFields.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all creative fields

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creative Fields'); - - do { - // Create and execute the creative fields list request. - $response = $this->service->creativeFields->listCreativeFields( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCreativeFields() as $fields) { - $this->printResultsTableRow($fields); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreativeFields()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creative Fields'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Field ID', - 'name' => 'Creative Field Name']; - } -} diff --git a/php/v3.5/examples/Creatives/GetCreativeGroups.php b/php/v3.5/examples/Creatives/GetCreativeGroups.php deleted file mode 100755 index f5ff243..0000000 --- a/php/v3.5/examples/Creatives/GetCreativeGroups.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all creative groups

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creative Groups'); - - do { - // Create and execute the creative fields list request. - $response = $this->service->creativeGroups->listCreativeGroups( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getCreativeGroups() as $groups) { - $this->printResultsTableRow($groups); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreativeGroups()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creative Groups'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative Group ID', - 'name' => 'Creative Group Name']; - } -} diff --git a/php/v3.5/examples/Creatives/GetCreatives.php b/php/v3.5/examples/Creatives/GetCreatives.php deleted file mode 100755 index 689b3f0..0000000 --- a/php/v3.5/examples/Creatives/GetCreatives.php +++ /dev/null @@ -1,101 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all active creatives for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Creatives'); - - do { - // Create and execute the creative fields list request. - $response = $this->service->creatives->listCreatives( - $values['user_profile_id'], - ['active' => true, - 'advertiserId' => $values['advertiser_id'], - 'pageToken' => $pageToken] - ); - - foreach ($response->getCreatives() as $creatives) { - $this->printResultsTableRow($creatives); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getCreatives()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Creatives'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Creative ID', - 'name' => 'Creative Name', - 'type' => 'Creative Type']; - } -} diff --git a/php/v3.5/examples/DimensionValues/GetDimensionValues.php b/php/v3.5/examples/DimensionValues/GetDimensionValues.php deleted file mode 100755 index ec0083e..0000000 --- a/php/v3.5/examples/DimensionValues/GetDimensionValues.php +++ /dev/null @@ -1,96 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'dimension_name', - 'display' => 'Dimension Name', - 'required' => true], - ['name' => 'start_date', - 'display' => 'Start Date (yyyy-MM-dd)', - 'required' => true], - ['name' => 'end_date', - 'display' => 'End Date (yyyy-MM-dd)', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $dimensionValueRequest = - new Google_Service_Dfareporting_DimensionValueRequest(); - $dimensionValueRequest->setDimensionName($values['dimension_name']); - $dimensionValueRequest->setStartDate($values['start_date']); - $dimensionValueRequest->setEndDate($values['end_date']); - - $dimensionValues = $this->service->dimensionValues->query( - $values['user_profile_id'], - $dimensionValueRequest - ); - - printf('

Listing available %s values

', $values['dimension_name']); - - $this->printResultsTable('Dimension Values', $dimensionValues['items']); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Dimension Values'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['value' => 'Dimension Value', - 'id' => 'Dimension ID']; - } -} diff --git a/php/v3.5/examples/Files/CheckFileStatus.php b/php/v3.5/examples/Files/CheckFileStatus.php deleted file mode 100755 index 8d2e4d2..0000000 --- a/php/v3.5/examples/Files/CheckFileStatus.php +++ /dev/null @@ -1,89 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true], - ['name' => 'report_file_id', - 'display' => 'Report File ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Getting status of report file with ID %s

', - $values['report_file_id'] - ); - - $reportFile = $this->service->reports_files->get( - $values['user_profile_id'], - $values['report_id'], - $values['report_file_id'] - ); - - $this->printResultsTable('File status', [$reportFile]); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Check File Generation Status'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status']; - } -} diff --git a/php/v3.5/examples/Files/GetAllFiles.php b/php/v3.5/examples/Files/GetAllFiles.php deleted file mode 100755 index b134ae3..0000000 --- a/php/v3.5/examples/Files/GetAllFiles.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all report files

'; - - $this->printResultsTableHeader('Files'); - - do { - $files = $this->service->files->listFiles( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($files['items'] as $file) { - $url = $file['urls']['browserUrl']; - $file['download'] = 'Link'; - $this->printResultsTableRow($file); - } - - $pageToken = $files['nextPageToken']; - } while (!empty($files['items']) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Files'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status', - 'download' => 'Download']; - } -} diff --git a/php/v3.5/examples/Floodlights/CreateFloodlightActivity.php b/php/v3.5/examples/Floodlights/CreateFloodlightActivity.php deleted file mode 100755 index 5bb5c31..0000000 --- a/php/v3.5/examples/Floodlights/CreateFloodlightActivity.php +++ /dev/null @@ -1,98 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'activity_group_id', - 'display' => 'Floodlight Activity Group ID', - 'required' => true], - ['name' => 'activity_name', - 'display' => 'Floodlight Activity Name', - 'required' => true], - ['name' => 'url', - 'display' => 'Expected URL', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating floodlight activity with name "%s" under group ID' - . ' %s

', - $values['activity_name'], - $values['activity_group_id'] - ); - - $activity = new Google_Service_Dfareporting_FloodlightActivity(); - $activity->setCountingMethod('STANDARD_COUNTING'); - $activity->setExpectedUrl($values['url']); - $activity->setFloodlightActivityGroupId($values['activity_group_id']); - $activity->setFloodlightTagType('GLOBAL_SITE_TAG'); - $activity->setName($values['activity_name']); - - $result = $this->service->floodlightActivities->insert( - $values['user_profile_id'], - $activity - ); - - $this->printResultsTable('Floodlight activity created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Floodlight Activity'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity ID', - 'name' => 'Floodlight Activity Name']; - } -} diff --git a/php/v3.5/examples/Floodlights/CreateFloodlightActivityGroup.php b/php/v3.5/examples/Floodlights/CreateFloodlightActivityGroup.php deleted file mode 100755 index 2fecef3..0000000 --- a/php/v3.5/examples/Floodlights/CreateFloodlightActivityGroup.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'group_name', - 'display' => 'Floodlight Activity Group Name', - 'required' => true], - ['name' => 'configuration_id', - 'display' => 'Floodlight Configuration (Advertiser) ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating floodlight activity group with name "%s"

', - $values['group_name'] - ); - - $group = new Google_Service_Dfareporting_FloodlightActivityGroup(); - $group->setFloodlightConfigurationId($values['configuration_id']); - $group->setName($values['group_name']); - $group->setType('COUNTER'); - - $result = $this->service->floodlightActivityGroups->insert( - $values['user_profile_id'], - $group - ); - - $this->printResultsTable('Floodlight activity group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Floodlight Activity Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity Group ID', - 'name' => 'Floodlight Activity Group Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.5/examples/Floodlights/DownloadFloodlightTags.php b/php/v3.5/examples/Floodlights/DownloadFloodlightTags.php deleted file mode 100755 index 1441677..0000000 --- a/php/v3.5/examples/Floodlights/DownloadFloodlightTags.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Downloading floodlight activity tags for activity ID %s

', - $values['activity_id'] - ); - - $result = $this->service->floodlightActivities->generatetag( - $values['user_profile_id'], - ['floodlightActivityId' => $values['activity_id']] - ); - - // Prepare the tag for display - $activityTag = ''; - if (!is_null($result->getGlobalSiteTagGlobalSnippet())) { - // This is a global site tag, display both the global and event snippets. - $activityTag = sprintf( - "Global site tag global snippet:\n\n%s", - $result->getGlobalSiteTagGlobalSnippet() - ); - $activityTag .= sprintf( - "\n\nGlobal site tag event snippet:\n\n%s", - $result->getFloodlightActivityTag() - ); - } else { - // This is an image or iframe tag. - $activityTag = sprintf( - "Floodlight activity tag:\n\n%s", - $result->getFloodlightActivityTag() - ); - } - - // Display the tag - print str_replace(["\r\n", "\n"], '
', htmlentities($activityTag)); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Download Floodlight Activity Tags'; - } -} diff --git a/php/v3.5/examples/Floodlights/GetFloodlightActivities.php b/php/v3.5/examples/Floodlights/GetFloodlightActivities.php deleted file mode 100755 index dcf7e1b..0000000 --- a/php/v3.5/examples/Floodlights/GetFloodlightActivities.php +++ /dev/null @@ -1,102 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all floodlight activities for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Floodlight Activities'); - - do { - // Create and execute the floodlight activities list request. - $response = - $this->service->floodlightActivities->listFloodlightActivities( - $values['user_profile_id'], - ['advertiserId' => $values['advertiser_id'], - 'pageToken' => $pageToken] - ); - - foreach ($response->getFloodlightActivities() as $activities) { - $this->printResultsTableRow($activities); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getFloodlightActivities()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Floodlight Activities'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity ID', - 'name' => 'Floodlight Activity Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.5/examples/Floodlights/GetFloodlightActivityGroups.php b/php/v3.5/examples/Floodlights/GetFloodlightActivityGroups.php deleted file mode 100755 index 3dce97d..0000000 --- a/php/v3.5/examples/Floodlights/GetFloodlightActivityGroups.php +++ /dev/null @@ -1,103 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all floodlight activity groups for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Floodlight Activity Groups'); - - $activityGroupService = $this->service->floodlightActivityGroups; - - do { - // Create and execute the floodlight activity groups list request. - $response = $activityGroupService->listFloodlightActivityGroups( - $values['user_profile_id'], - ['advertiserId' => $values['advertiser_id'], - 'pageToken' => $pageToken] - ); - - foreach ($response->getFloodlightActivityGroups() as $groups) { - $this->printResultsTableRow($groups); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getFloodlightActivityGroups()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Floodlight Activity Groups'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Floodlight Activity Group ID', - 'name' => 'Floodlight Activity Group Name', - 'floodlightConfigurationId' => 'Floodlight Configuration ID']; - } -} diff --git a/php/v3.5/examples/Misc/GetChangeLogsForAdvertiser.php b/php/v3.5/examples/Misc/GetChangeLogsForAdvertiser.php deleted file mode 100755 index 7a8a7ba..0000000 --- a/php/v3.5/examples/Misc/GetChangeLogsForAdvertiser.php +++ /dev/null @@ -1,104 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all change logs for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Change Logs'); - - do { - // Create and execute the change logs list request. - $response = $this->service->changeLogs->listChangeLogs( - $values['user_profile_id'], - ['objectIds' => [$values['advertiser_id']], - 'objectType' => 'OBJECT_ADVERTISER', - 'pageToken' => $pageToken] - ); - - foreach ($response->getChangeLogs() as $log) { - $this->printResultsTableRow($log); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getChangeLogs()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Change Logs For Advertiser'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['action' => 'Action', - 'fieldName' => 'Field', - 'oldValue' => 'Old Value', - 'newValue' => 'New Value']; - } -} diff --git a/php/v3.5/examples/Misc/GetSites.php b/php/v3.5/examples/Misc/GetSites.php deleted file mode 100755 index 5ef571f..0000000 --- a/php/v3.5/examples/Misc/GetSites.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all sites

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Sites'); - - do { - // Create and execute the sites list request. - $response = $this->service->sites->listSites( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getSites() as $sites) { - $this->printResultsTableRow($sites); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getSites()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Sites'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Site ID', - 'keyName' => 'Site Key Name']; - } -} diff --git a/php/v3.5/examples/Misc/GetSize.php b/php/v3.5/examples/Misc/GetSize.php deleted file mode 100755 index 267d868..0000000 --- a/php/v3.5/examples/Misc/GetSize.php +++ /dev/null @@ -1,94 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'width', - 'display' => 'Width (px)', - 'required' => true], - ['name' => 'height', - 'display' => 'Height (px)', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing sizes matching %sx%s

', - $values['width']. $values['height'] - ); - - $this->printResultsTableHeader('Sizes'); - - // Create and execute the size list request. - $response = $this->service->sizes->listSizes( - $values['user_profile_id'], - ['height' => $values['height'], - 'width' => $values['width']] - ); - - foreach ($response->getSizes() as $sizes) { - $this->printResultsTableRow($sizes); - } - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Size'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Size ID', - 'width' => 'Width', - 'height' => 'Height']; - } -} diff --git a/php/v3.5/examples/Placements/CreateContentCategory.php b/php/v3.5/examples/Placements/CreateContentCategory.php deleted file mode 100755 index ffa66ed..0000000 --- a/php/v3.5/examples/Placements/CreateContentCategory.php +++ /dev/null @@ -1,85 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'category_name', - 'display' => 'Content Category Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating content category with name "%s"

', - $values['category_name'] - ); - - $category = new Google_Service_Dfareporting_ContentCategory(); - $category->setName($values['category_name']); - - $result = $this->service->contentCategories->insert( - $values['user_profile_id'], - $category - ); - - $this->printResultsTable('Content category created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Content Category'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Content Category ID', - 'name' => 'Content Category Name']; - } -} diff --git a/php/v3.5/examples/Placements/CreatePlacement.php b/php/v3.5/examples/Placements/CreatePlacement.php deleted file mode 100755 index e6fccd5..0000000 --- a/php/v3.5/examples/Placements/CreatePlacement.php +++ /dev/null @@ -1,122 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'site_id', - 'display' => 'Site ID', - 'required' => true], - ['name' => 'size_id', - 'display' => 'Size ID', - 'required' => true], - ['name' => 'placement_name', - 'display' => 'Placement Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating placement with name "%s" under campaign ID %s

', - $values['placement_name'], - $values['campaign_id'] - ); - - // Retrieve the campaign. - $campaign = $this->service->campaigns->get( - $values['user_profile_id'], - $values['campaign_id'] - ); - - $placement = new Google_Service_Dfareporting_Placement(); - $placement->setCampaignId($values['campaign_id']); - $placement->setCompatibility('DISPLAY'); - $placement->setName($values['placement_name']); - $placement->setPaymentSource('PLACEMENT_AGENCY_PAID'); - $placement->setSiteId($values['site_id']); - $placement->setTagFormats(['PLACEMENT_TAG_STANDARD']); - - // Set the size of the placement. - $size = new Google_Service_Dfareporting_Size(); - $size->setId($values['size_id']); - $placement->setSize($size); - - // Set the pricing schedule for the placement. - $pricingSchedule = new Google_Service_Dfareporting_PricingSchedule(); - $pricingSchedule->setEndDate($campaign->getEndDate()); - $pricingSchedule->setPricingType('PRICING_TYPE_CPM'); - $pricingSchedule->setStartDate($campaign->getStartDate()); - $placement->setPricingSchedule($pricingSchedule); - - // Insert the placement. - $result = $this->service->placements->insert( - $values['user_profile_id'], - $placement - ); - - $this->printResultsTable('Placement created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Placement'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement ID', - 'name' => 'Placement Name']; - } -} diff --git a/php/v3.5/examples/Placements/CreatePlacementGroup.php b/php/v3.5/examples/Placements/CreatePlacementGroup.php deleted file mode 100755 index 8a18378..0000000 --- a/php/v3.5/examples/Placements/CreatePlacementGroup.php +++ /dev/null @@ -1,111 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'site_id', - 'display' => 'Site ID', - 'required' => true], - ['name' => 'group_name', - 'display' => 'Placement Group Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating placement group with name "%s" under campaign ID %s

', - $values['group_name'], - $values['campaign_id'] - ); - - // Retrieve the campaign. - $campaign = $this->service->campaigns->get( - $values['user_profile_id'], - $values['campaign_id'] - ); - - $group = new Google_Service_Dfareporting_PlacementGroup(); - $group->setCampaignId($values['campaign_id']); - $group->setName($values['group_name']); - $group->setPlacementGroupType('PLACEMENT_PACKAGE'); - $group->setSiteId($values['site_id']); - - // Set the pricing schedule for the placement group. - $pricingSchedule = new Google_Service_Dfareporting_PricingSchedule(); - $pricingSchedule->setEndDate($campaign->getEndDate()); - $pricingSchedule->setPricingType('PRICING_TYPE_CPM'); - $pricingSchedule->setStartDate($campaign->getStartDate()); - $group->setPricingSchedule($pricingSchedule); - - // Insert the placement group. - $result = $this->service->placementGroups->insert( - $values['user_profile_id'], - $group - ); - - $this->printResultsTable('Placement group created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Placement Group'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement Group ID', - 'name' => 'Placement Group Name']; - } -} diff --git a/php/v3.5/examples/Placements/CreatePlacementStrategy.php b/php/v3.5/examples/Placements/CreatePlacementStrategy.php deleted file mode 100755 index dbc3077..0000000 --- a/php/v3.5/examples/Placements/CreatePlacementStrategy.php +++ /dev/null @@ -1,85 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'strategy_name', - 'display' => 'Placement Strategy Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating placement strategy with name "%s"

', - $values['strategy_name'] - ); - - $strategy = new Google_Service_Dfareporting_PlacementStrategy(); - $strategy->setName($values['strategy_name']); - - $result = $this->service->placementStrategies->insert( - $values['user_profile_id'], - $strategy - ); - - $this->printResultsTable('Placement strategy created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Placement Strategy'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement Strategy ID', - 'name' => 'Placement Strategy Name']; - } -} diff --git a/php/v3.5/examples/Placements/DownloadPlacementTags.php b/php/v3.5/examples/Placements/DownloadPlacementTags.php deleted file mode 100755 index 6b5ab42..0000000 --- a/php/v3.5/examples/Placements/DownloadPlacementTags.php +++ /dev/null @@ -1,106 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'campaign_id', - 'display' => 'Campaign ID', - 'required' => true], - ['name' => 'placement_id', - 'display' => 'Placement ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Downloading placement tags for placement ID %s

', - $values['placement_id'] - ); - - $placementTags = $this->service->placements->generatetags( - $values['user_profile_id'], - ['campaignId' => $values['campaign_id'], - 'placementIds' => [$values['placement_id']], - 'tagFormats' => ['PLACEMENT_TAG_STANDARD', - 'PLACEMENT_TAG_IFRAME_JAVASCRIPT', - 'PLACEMENT_TAG_INTERNAL_REDIRECT'] - ] - ); - - $this->printResultsTableHeader('Placement Tags'); - - foreach ($placementTags['placementTags'] as $placementTag) { - foreach ($placementTag['tagDatas'] as $tagData) { - $result = ['clickTag' => htmlspecialchars($tagData->getClickTag()), - 'format' => $tagData->getFormat(), - 'impressionTag' => - htmlspecialchars($tagData->getImpressionTag())]; - - $this->printResultsTableRow($result); - } - } - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Download Placement Tags'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['format' => 'Format', - 'impressionTag' => 'Impression Tag', - 'clickTag' => 'Click Tag']; - } -} diff --git a/php/v3.5/examples/Placements/GetContentCategories.php b/php/v3.5/examples/Placements/GetContentCategories.php deleted file mode 100755 index 1a69d52..0000000 --- a/php/v3.5/examples/Placements/GetContentCategories.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all content categories

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Content Categories'); - - do { - // Create and execute the content categories list request. - $response = $this->service->contentCategories->listContentCategories( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getContentCategories() as $categories) { - $this->printResultsTableRow($categories); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getContentCategories()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Content Categories'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Content Category ID', - 'name' => 'Content Category Name']; - } -} diff --git a/php/v3.5/examples/Placements/GetPlacementStrategies.php b/php/v3.5/examples/Placements/GetPlacementStrategies.php deleted file mode 100755 index c11f5fc..0000000 --- a/php/v3.5/examples/Placements/GetPlacementStrategies.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all placement strategies

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Placement Strategies'); - - do { - // Create and execute the placement strategies list request. - $response = $this->service->placementStrategies->listPlacementStrategies( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getPlacementStrategies() as $strategies) { - $this->printResultsTableRow($strategies); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getPlacementStrategies()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Placement Strategies'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement Strategy ID', - 'name' => 'Placement Strategy Name']; - } -} diff --git a/php/v3.5/examples/Placements/GetPlacements.php b/php/v3.5/examples/Placements/GetPlacements.php deleted file mode 100755 index 079e0b6..0000000 --- a/php/v3.5/examples/Placements/GetPlacements.php +++ /dev/null @@ -1,92 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all placements

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Placements'); - - do { - // Create and execute the placements list request. - $response = $this->service->placements->listPlacements( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getPlacements() as $placements) { - $this->printResultsTableRow($placements); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getPlacements()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Placements'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Placement ID', - 'name' => 'Placement Name', - 'campaignId' => 'Associated Campaign ID']; - } -} diff --git a/php/v3.5/examples/RemarketingLists/CreateRemarketingList.php b/php/v3.5/examples/RemarketingLists/CreateRemarketingList.php deleted file mode 100755 index f361783..0000000 --- a/php/v3.5/examples/RemarketingLists/CreateRemarketingList.php +++ /dev/null @@ -1,122 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'floodlight_activity_id', - 'display' => 'Floodlight Activity ID', - 'required' => true], - ['name' => 'remarketing_list_name', - 'display' => 'Remarketing List Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating remarketing list with name "%s"

', - $values['remarketing_list_name'] - ); - - // Create the remarketing list. - $list = new Google_Service_Dfareporting_RemarketingList(); - $list->setActive(true); - $list->setAdvertiserId($values['advertiser_id']); - $list->setLifeSpan(30); - $list->setName($values['remarketing_list_name']); - - // Create a list population term. - // This term matches all visitors with a U1 value exactly matching - // "test_value". - $term = new Google_Service_Dfareporting_ListPopulationTerm(); - $term->setOperator('STRING_EQUALS'); - $term->setType('CUSTOM_VARIABLE_TERM'); - $term->setValue('test_value'); - $term->setVariableName('U1'); - - // Add the term to a list population clause. - $clause = new Google_Service_Dfareporting_ListPopulationClause(); - $clause->setTerms([$term]); - - // Add the clause to a list population rule. - // This rule will target all visitors who trigger the specified floodlight - // activity and satisfy the custom rule defined in the list population term. - $rule = new Google_Service_Dfareporting_ListPopulationRule(); - $rule->setFloodlightActivityId($values['floodlight_activity_id']); - $rule->setListPopulationClauses([$clause]); - - $list->setListPopulationRule($rule); - - // Insert the remarketing list. - $result = $this->service->remarketingLists->insert( - $values['user_profile_id'], - $list - ); - - $this->printResultsTable('Remarketing list created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Remarketing List'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Remarketing List ID', - 'name' => 'Remarketing List Name']; - } -} diff --git a/php/v3.5/examples/RemarketingLists/GetRemarketingLists.php b/php/v3.5/examples/RemarketingLists/GetRemarketingLists.php deleted file mode 100755 index 7f2117a..0000000 --- a/php/v3.5/examples/RemarketingLists/GetRemarketingLists.php +++ /dev/null @@ -1,104 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all remarketing lists for advertiser ID %s

', - $values['advertiser_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Remarketing Lists'); - - do { - // Create and execute the remarketing lists list request. - $response = $this->service->remarketingLists->listRemarketingLists( - $values['user_profile_id'], - $values['advertiser_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getRemarketingLists() as $list) { - $this->printResultsTableRow($list); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getRemarketingLists()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Remarketing Lists'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Remarketing List ID', - 'name' => 'Remarketing List Name']; - } -} diff --git a/php/v3.5/examples/RemarketingLists/ShareRemarketingList.php b/php/v3.5/examples/RemarketingLists/ShareRemarketingList.php deleted file mode 100755 index ca0a17d..0000000 --- a/php/v3.5/examples/RemarketingLists/ShareRemarketingList.php +++ /dev/null @@ -1,108 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'list_id', - 'display' => 'Remarketing List ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Sharing remarketing list %s with advertiser ID %s

', - $values['list_id'], - $values['advertiser_id'] - ); - - // Load the existing share info. - $share = $this->service->remarketingListShares->get( - $values['user_profile_id'], - $values['list_id'] - ); - - $advertiserIds = $share['sharedAdvertiserIds']; - if (!isset($advertiserIds)) { - $advertiserIds = []; - } - - if (!in_array($values['advertiser_id'], $advertiserIds)) { - // Add the specified advertiser to the list of shared advertisers. - $advertiserIds[] = $values['advertiser_id']; - $share->setSharedAdvertiserIds($advertiserIds); - - // Update the share info with the newly added advertiser. - $result = $this->service->remarketingListShares->update( - $values['user_profile_id'], - $share - ); - - $result['advertiserIds'] = implode(',', $result['sharedAdvertiserIds']); - $this->printResultsTable('Remarketing list shared.', [$result]); - } else { - print '
Remarketing list is already shared with advertiser.
'; - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Share Remarketing List With Advertiser'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['remarketingListId' => 'Remarketing List ID', - 'advertiserIds' => 'Shared Advertiser IDs']; - } -} diff --git a/php/v3.5/examples/RemarketingLists/TargetAdToRemarketingList.php b/php/v3.5/examples/RemarketingLists/TargetAdToRemarketingList.php deleted file mode 100755 index 8456727..0000000 --- a/php/v3.5/examples/RemarketingLists/TargetAdToRemarketingList.php +++ /dev/null @@ -1,117 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'ad_id', - 'display' => 'Ad ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Targeting ad %s to a targetable remarketing list.

', - $values['ad_id'] - ); - - // Load the specified ad. - $ad = $this->service->ads->get( - $values['user_profile_id'], - $values['ad_id'] - ); - - // Find a targetable remarketing list for this ad's advertiser. - $listService = $this->service->targetableRemarketingLists; - $lists = $listService->listTargetableRemarketingLists( - $values['user_profile_id'], - $ad['advertiserId'], - ['maxResults' => 1] - ); - - if (!empty($lists['targetableRemarketingLists'])) { - // Select the first targetable remarketing list that was returned. - $list = $lists['targetableRemarketingLists'][0]; - - // Create a list targeting expression. - $expression = new Google_Service_Dfareporting_ListTargetingExpression(); - $expression->setExpression(strval($list['id'])); - - // Update the ad. - $ad->setRemarketingListExpression($expression); - $result = $this->service->ads->update( - $values['user_profile_id'], - $ad - ); - - $result['expression'] = - $result['remarketing_list_expression']['expression']; - - $this->printResultsTable('Ad targeted to remarketing list.', [$result]); - } else { - print '
Ad has no targetable remarketing lists.
'; - } - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Target Ad to a Remarketing List'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Ad ID', - 'expression' => 'Remarketing List Expression']; - } -} diff --git a/php/v3.5/examples/Reports/CreateStandardReport.php b/php/v3.5/examples/Reports/CreateStandardReport.php deleted file mode 100755 index f2e69e4..0000000 --- a/php/v3.5/examples/Reports/CreateStandardReport.php +++ /dev/null @@ -1,186 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Creating a new standard report

'; - $this->flush(); - - $userProfileId = $values['user_profile_id']; - - // 1. Create a report resource. - $report = $this->createReportResource(); - - // 2. Define the report criteria. - $this->defineReportCriteria($report); - - // 3. (optional) Look up compatible fields. - $this->findCompatibleFields($userProfileId, $report); - - // 4. Add dimension filters to the report criteria. - $this->addDimensionFilters($userProfileId, $report); - - // 5. Save the report resource. - $report = $this->insertReportResource($userProfileId, $report); - - $this->printResultsTable('Standard Report', [$report]); - } - - private function createReportResource() - { - $report = new Google_Service_Dfareporting_Report(); - - // Set the required fields "name" and "type". - $report->setName('Example standard report'); - $report->setType('STANDARD'); - - // Set optional fields. - $report->setFileName('example_report'); - $report->setFormat('CSV'); - - return $report; - } - - private function defineReportCriteria($report) - { - // Define a date range to report on. This example uses explicit start and - // end dates to mimic the "LAST_30_DAYS" relative date range. - $dateRange = new Google_Service_Dfareporting_DateRange(); - $dateRange->setStartDate( - date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 30, date('Y'))) - ); - $dateRange->setEndDate(date('Y-m-d')); - - // Create a report criteria. - $dimension = new Google_Service_Dfareporting_SortedDimension(); - $dimension->setName('advertiser'); - - $criteria = new Google_Service_Dfareporting_ReportCriteria(); - $criteria->setDateRange($dateRange); - $criteria->setDimensions([$dimension]); - $criteria->setMetricNames(['clicks', 'impressions']); - - // Add the criteria to the report resource. - $report->setCriteria($criteria); - } - - private function findCompatibleFields($userProfileId, $report) - { - $fields = $this->service->reports_compatibleFields->query( - $userProfileId, - $report - ); - - $reportFields = $fields->getReportCompatibleFields(); - - if (!empty($reportFields->getDimensions())) { - // Add a compatible dimension to the report. - $dimension = $reportFields->getDimensions()[0]; - $sortedDimension = new Google_Service_Dfareporting_SortedDimension(); - $sortedDimension->setName($dimension->getName()); - $report->getCriteria()->setDimensions( - array_merge( - $report->getCriteria()->getDimensions(), - [$sortedDimension] - ) - ); - } elseif (!empty($reportFields->getMetrics())) { - // Add a compatible metric to the report. - $metric = $reportFields->getMetrics()[0]; - $report->getCriteria()->setMetricNames( - array_merge( - $report->getCriteria()->getMetricNames(), - [$metric->getName()] - ) - ); - } - } - - private function addDimensionFilters($userProfileId, $report) - { - // Query advertiser dimension values for report run dates. - $request = new Google_Service_Dfareporting_DimensionValueRequest(); - $request->setStartDate( - $report->getCriteria()->getDateRange()->getStartDate() - ); - $request->setEndDate( - $report->getCriteria()->getDateRange()->getEndDate() - ); - $request->setDimensionName('advertiser'); - - $values = - $this->service->dimensionValues->query($userProfileId, $request); - - if (!empty($values->getItems())) { - // Add a value as a filter to the report criteria. - $report->getCriteria()->setDimensionFilters([$values->getItems()[0]]); - } - } - - private function insertReportResource($userProfileId, $report) - { - $insertedReport = - $this->service->reports->insert($userProfileId, $report); - return $insertedReport; - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Standard Report'; - } - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Report ID', - 'name' => 'Report Name']; - } -} diff --git a/php/v3.5/examples/Reports/DeleteReport.php b/php/v3.5/examples/Reports/DeleteReport.php deleted file mode 100755 index 5cbc480..0000000 --- a/php/v3.5/examples/Reports/DeleteReport.php +++ /dev/null @@ -1,68 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf('

Deleting report with ID %s

', $values['report_id']); - - $this->service->reports->delete( - $values['user_profile_id'], - $values['report_id'] - ); - - print '
Success
'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Delete Report'; - } -} diff --git a/php/v3.5/examples/Reports/DownloadReportFile.php b/php/v3.5/examples/Reports/DownloadReportFile.php deleted file mode 100755 index ef72ddf..0000000 --- a/php/v3.5/examples/Reports/DownloadReportFile.php +++ /dev/null @@ -1,180 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true], - ['name' => 'file_id', - 'display' => 'Report File ID']]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $reportId = $values['report_id']; - $userProfileId = $values['user_profile_id']; - - // 1. Find a file to download. - $fileId = $values['file_id']; - if (empty($fileId)) { - $fileId = $this->findFile($userProfileId, $reportId); - } - - if (!empty($fileId)) { - printf( - '

Retrieving contents of file %d for report %d

', - $fileId, - $reportId - ); - $this->flush(); - - // 2. (optional) Generate browser URL. - $this->generateBrowserUrl($reportId, $fileId); - $this->flush(); - - // 3. Directly download the file. - $this->directDownloadFile($reportId, $fileId); - } else { - printf( - '

No file found for profile ID %d and report ID %d

', - $userProfileId, - $reportId - ); - } - } - - private function findFile($userProfileId, $reportId) - { - $target = null; - $response = null; - $pageToken = null; - - do { - // Create and execute the file list request. - $response = $this->service->reports_files->listReportsFiles( - $userProfileId, - $reportId, - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $file) { - if ($this->isTargetFile($file)) { - $target = $file; - break; - } - } - - $pageToken = $response->getNextPageToken(); - } while (empty($target) && !empty($response->getItems()) && !empty($pageToken)); - - return is_null($target) ? null : $target->getId(); - } - - private function isTargetFile($file) - { - // Provide custom validation logic here. - // For example purposes, any file with REPORT_AVAILABLE status is - // considered valid. - return $file->getStatus() === 'REPORT_AVAILABLE'; - } - - private function generateBrowserUrl($reportId, $fileId) - { - $file = $this->service->files->get($reportId, $fileId); - $browserUrl = $file->getUrls()->getBrowserUrl(); - - printf( - '

Report file has browser URL: %s

', - $browserUrl, - $browserUrl - ); - } - - private function directDownloadFile($reportId, $fileId) - { - // Retrieve the file metadata. - $file = $this->service->files->get($reportId, $fileId); - - if ($file->getStatus() === 'REPORT_AVAILABLE') { - try { - // Prepare a local file to download the report contents to. - $fileName = join( - DIRECTORY_SEPARATOR, - [sys_get_temp_dir(), $this->generateFileName($file)] - ); - $fileResource = fopen($fileName, 'w+'); - $fileStream = \GuzzleHttp\Psr7\stream_for($fileResource); - - // Execute the get request and download the file. - $httpClient = $this->service->getClient()->authorize(); - $result = $httpClient->request( - 'GET', - $file->getUrls()->getApiUrl(), - [\GuzzleHttp\RequestOptions::SINK => $fileStream] - ); - - printf('

Report file saved to: %s

', $fileName); - print '

Report file contents:

'; - print nl2br(file_get_contents($fileName)); - } finally { - $fileStream->close(); - fclose($fileResource); - } - } - } - - private function generateFileName($file) - { - $fileName = $file->getFileName() ?: $file->getId(); - $extension = $file->getFormat() === 'CSV' ? '.csv' : '.xls'; - - return $fileName . $extension; - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Download Report File'; - } -} diff --git a/php/v3.5/examples/Reports/GenerateReportFile.php b/php/v3.5/examples/Reports/GenerateReportFile.php deleted file mode 100755 index c6fab12..0000000 --- a/php/v3.5/examples/Reports/GenerateReportFile.php +++ /dev/null @@ -1,210 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID']]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $userProfileId = $values['user_profile_id']; - - // 1. Find a report to run. - $reportId = $values['report_id']; - if (empty($reportId)) { - $reportId = $this->findReport($userProfileId); - } - - if (!empty($reportId)) { - printf( - '

Generating a report file for report with ID %d

', - $reportId - ); - $this->flush(); - - // 2. Run the report. - $file = $this->runReport($userProfileId, $reportId); - $this->flush(); - - // 3. Wait for the report file to be ready. - $file = $this->waitForReportFile($reportId, $file->getId()); - $this->flush(); - - if (!empty($file)) { - $this->printResultsTable('Report File', [$file]); - } - } else { - printf('

No report found for profile ID %d

', $userProfileId); - } - } - - private function findReport($userProfileId) - { - $target = null; - $response = null; - $pageToken = null; - - do { - // Create and execute the report list request. - $response = $this->service->reports->listReports( - $userProfileId, - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $report) { - if ($this->isTargetReport($report)) { - $target = $report; - break; - } - } - - $pageToken = $response->getNextPageToken(); - } while (empty($target) && !empty($response->getItems()) && !empty($pageToken)); - - return is_null($target) ? null : $target->getId(); - } - - private function isTargetReport($file) - { - // Provide custom validation logic here. - // For example purposes, any report is considered valid. - return true; - } - - private function runReport($userProfileId, $reportId) - { - // Run the report. - $file = $this->service->reports->run($userProfileId, $reportId); - - printf( - 'Running report %d, current file status is %s
', - $reportId, - $file->getStatus() - ); - return $file; - } - - private function waitForReportFile($reportId, $fileId) - { - // Wait for the report file to finish processing. - // An exponential backoff policy is used to limit retries and conserve - // quota. - $sleep = 0; - $startTime = time(); - - do { - $file = $this->service->files->get($reportId, $fileId); - - if ($file->getStatus() === 'REPORT_AVAILABLE') { - printf('File status is %s, ready to download
', $file->getStatus()); - return $file; - } elseif ($file->getStatus() !== 'PROCESSING') { - printf('File status is %s, processing failed
', $file->getStatus()); - return null; - } elseif (time() - $startTime > self::MAX_RETRY_ELAPSED_TIME) { - printf('File processing deadline exceeded
'); - return null; - } - - $sleep = $this->getNextSleepInterval($sleep); - printf( - 'File status is %s, sleeping for %d seconds
', - $file->getStatus(), - $sleep - ); - $this->sleep($sleep); - } while (true); - } - - private function getNextSleepInterval($previousSleepInterval) - { - $minInterval = max(self::MIN_RETRY_INTERVAL, $previousSleepInterval); - $maxInterval = max(self::MIN_RETRY_INTERVAL, $previousSleepInterval * 3); - return min(self::MAX_RETRY_INTERVAL, rand($minInterval, $maxInterval)); - } - - private function sleep($interval) - { - $startTime = time(); - do { - // Flush regularly to prevent timeouts. - $this->flush(); - sleep(1); - - if (time() - $startTime >= $interval) { - return; - } - } while (true); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Generate Report File'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status']; - } -} diff --git a/php/v3.5/examples/Reports/GetAllReportFiles.php b/php/v3.5/examples/Reports/GetAllReportFiles.php deleted file mode 100755 index f0d4653..0000000 --- a/php/v3.5/examples/Reports/GetAllReportFiles.php +++ /dev/null @@ -1,101 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing all files for report with ID %s

', - $values['report_id'] - ); - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Report Files'); - - do { - $response = $this->service->reports_files->listReportsFiles( - $values['user_profile_id'], - $values['report_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $file) { - $file['apiUrl'] = $file->getUrls()->getApiUrl(); - $this->printResultsTableRow($file); - } - - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getItems()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Report Files'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'File ID', - 'fileName' => 'File Name', - 'reportId' => 'Report ID', - 'format' => 'File Format', - 'status' => 'Status', - 'apiUrl' => 'API URL']; - } -} diff --git a/php/v3.5/examples/Reports/GetAllReports.php b/php/v3.5/examples/Reports/GetAllReports.php deleted file mode 100755 index adb89b1..0000000 --- a/php/v3.5/examples/Reports/GetAllReports.php +++ /dev/null @@ -1,90 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all reports

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Reports'); - do { - $response = $this->service->reports->listReports( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getItems() as $report) { - $this->printResultsTableRow($report); - } - - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getItems()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Reports'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Report ID', - 'name' => 'Report Name', - 'type' => 'Report Type']; - } -} diff --git a/php/v3.5/examples/Reports/GetCompatibleFields.php b/php/v3.5/examples/Reports/GetCompatibleFields.php deleted file mode 100755 index 8f2cd32..0000000 --- a/php/v3.5/examples/Reports/GetCompatibleFields.php +++ /dev/null @@ -1,110 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'report_id', - 'display' => 'Report ID', - 'required' => true]]; - } - - /** - * {@inheritdoc} - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Listing compatible fields for report with ID %s

', - $values['report_id'] - ); - - // Retrieve the specified report - $report = $this->service->reports->get( - $values['user_profile_id'], - $values['report_id'] - ); - - // Look up the compatible fields for this report - $fields = $this->service->reports_compatibleFields->query( - $values['user_profile_id'], - $report - ); - - // Print the compatible dimensions - $this->printResultsTable( - 'Dimensions', - $fields->getReportCompatibleFields()->getDimensions() - ); - - // Print the compatible metrics - $this->printResultsTable( - 'Metrics', - $fields->getReportCompatibleFields()->getMetrics() - ); - - // Print the compatible dimension filters - $this->printResultsTable( - 'Dimension Filters', - $fields->getReportCompatibleFields()->getDimensionFilters() - ); - - // Print the compatible pivoted activity metrics - $this->printResultsTable( - 'Pivoted Activity Metrics', - $fields->getReportCompatibleFields()->getPivotedActivityMetrics() - ); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Compatible Fields'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['name' => 'Field Name']; - } -} diff --git a/php/v3.5/examples/Subaccounts/CreateSubaccount.php b/php/v3.5/examples/Subaccounts/CreateSubaccount.php deleted file mode 100755 index a5e05fb..0000000 --- a/php/v3.5/examples/Subaccounts/CreateSubaccount.php +++ /dev/null @@ -1,99 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'account_id', - 'display' => 'Account ID', - 'required' => true], - ['name' => 'permission_one', - 'display' => 'First Permission ID', - 'required' => true], - ['name' => 'permission_two', - 'display' => 'Second Permission ID', - 'required' => true], - ['name' => 'subaccount_name', - 'display' => 'Subaccount Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating subaccount with name "%s" for account ID %s

', - $values['subaccount_name'], - $values['account_id'] - ); - - $subaccount = new Google_Service_Dfareporting_Subaccount(); - $subaccount->setName($values['subaccount_name']); - $subaccount->setAvailablePermissionIds( - [$values['permission_one'], $values['permission_two']] - ); - - $result = $this->service->subaccounts->insert( - $values['user_profile_id'], - $subaccount - ); - - $this->printResultsTable('Subaccount created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Subaccount'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Subaccount ID', - 'name' => 'Subaccount Name']; - } -} diff --git a/php/v3.5/examples/Subaccounts/GetSubaccountPermissions.php b/php/v3.5/examples/Subaccounts/GetSubaccountPermissions.php deleted file mode 100755 index 8370a99..0000000 --- a/php/v3.5/examples/Subaccounts/GetSubaccountPermissions.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'subaccount_id', - 'display' => 'Subaccount ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - $subaccount = $this->service->subaccounts->get( - $values['user_profile_id'], - $values['subaccount_id'] - ); - - printf( - '

Listing all permissions for subaccount "%s"

', - $subaccount->getName() - ); - - $permissions = - $this->service->userRolePermissions->listUserRolePermissions( - $values['user_profile_id'], - ['ids' => $subaccount->getAvailablePermissionIds()] - ); - - $this->printResultsTable('Subaccount Permissions', $permissions); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get Subaccount Permissions'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Permission ID', - 'name' => 'Permission Name']; - } -} diff --git a/php/v3.5/examples/Subaccounts/GetSubaccounts.php b/php/v3.5/examples/Subaccounts/GetSubaccounts.php deleted file mode 100755 index 28df915..0000000 --- a/php/v3.5/examples/Subaccounts/GetSubaccounts.php +++ /dev/null @@ -1,91 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all subaccounts

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Subaccounts'); - - do { - // Create and execute the subaccounts list request. - $response = $this->service->subaccounts->listSubaccounts( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getSubaccounts() as $subaccount) { - $this->printResultsTableRow($subaccount); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getSubaccounts()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Subaccounts'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Subaccount ID', - 'name' => 'Subaccount Name']; - } -} diff --git a/php/v3.5/examples/TargetingTemplates/ConfigureDynamicAssetSelection.php b/php/v3.5/examples/TargetingTemplates/ConfigureDynamicAssetSelection.php deleted file mode 100755 index 2bacb71..0000000 --- a/php/v3.5/examples/TargetingTemplates/ConfigureDynamicAssetSelection.php +++ /dev/null @@ -1,158 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'creative_id', - 'display' => 'In-stream Video Creative ID', - 'required' => true], - ['name' => 'template_id', - 'display' => 'Targeting Template ID', - 'required' => true], - ['name' => 'asset_file', - 'display' => 'Video Asset File', - 'file' => true, - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Configuring dynamic asset selection for creative ID %s

', - $values['creative_id'] - ); - - // Retrieve the specified creative. - $creative = $this->service->creatives->get( - $values['user_profile_id'], - $values['creative_id'] - ); - if (is_null($creative) || strcmp($creative->getType(), 'INSTREAM_VIDEO') !== 0) { - print 'Invalid creative specified.'; - return; - } - - $assetSelection = $creative->getCreativeAssetSelection(); - if (!$creative->getDynamicAssetSelection()) { - // Locate an existing video asset to use as a default. - // This example uses the first PARENT_VIDEO asset found. - $defaultVideoAssetId = $this->findDefaultVideoAssetId($creative); - if ($defaultVideoAssetId < 0) { - print 'Default video asset could not be found.'; - return; - } - - // Create a new selection using the existing asset as a default. - $assetSelection = - new Google_Service_Dfareporting_CreativeAssetSelection(); - $assetSelection->setDefaultAssetId($defaultVideoAssetId); - $assetSelection->setRules([]); - - // Enable dynamic asset selection for the creative. - $creative->setDynamicAssetSelection(true); - $creative->setCreativeAssetSelection($assetSelection); - } - - // Upload the new video asset and add it to the creative. - $video = uploadAsset( - $this->service, - $values['user_profile_id'], - $creative->getAdvertiserId(), - $values['asset_file'], - 'VIDEO' - ); - $videoAsset = new Google_Service_Dfareporting_CreativeAsset(); - $videoAsset->setAssetIdentifier($video->getAssetIdentifier()); - $videoAsset->setRole('PARENT_VIDEO'); - $creative->setCreativeAssets( - array_merge($creative->getCreativeAssets(), [$videoAsset]) - ); - - // Create a rule targeting the new video asset and add it to the selection. - $rule = new Google_Service_Dfareporting_Rule(); - $rule->setAssetId($video->getId()); - $rule->setName('Test rule for asset ' . $video->getId()); - $rule->setTargetingTemplateId($values['template_id']); - $assetSelection->setRules( - array_merge($assetSelection->getRules(), [$rule]) - ); - - // Update the creative. - $result = $this->service->creatives->update( - $values['user_profile_id'], - $creative - ); - - printf( - 'Dynamic asset selection enabled for creative with ID %d.', - $result->getId() - ); - } - - private function findDefaultVideoAssetId($creative) - { - $assets = $creative->getCreativeAssets(); - $index = array_search( - 'PARENT_VIDEO', - array_map( - function ($asset) { - return $asset->getRole(); - }, - $assets - ) - ); - - return $index !== false ? $assets[$index]->getId() : -1; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Configure Dynamic Asset Targeting'; - } -} diff --git a/php/v3.5/examples/TargetingTemplates/CreateTargetingTemplate.php b/php/v3.5/examples/TargetingTemplates/CreateTargetingTemplate.php deleted file mode 100755 index cf1131a..0000000 --- a/php/v3.5/examples/TargetingTemplates/CreateTargetingTemplate.php +++ /dev/null @@ -1,100 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'advertiser_id', - 'display' => 'Advertiser ID', - 'required' => true], - ['name' => 'template_name', - 'display' => 'Template Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating targeting template "%s" for advertiser ID %s

', - $values['template_name'], - $values['advertiser_id'] - ); - - // Create the targeting template. - $template = new Google_Service_Dfareporting_TargetingTemplate(); - $template->setAdvertiserId($values['advertiser_id']); - $template->setName($values['template_name']); - - // Configure the template to serve ads on Monday, Wednesday, and Friday from - // 9 to 10am and 3 to 5pm. - $targeting = new Google_Service_Dfareporting_DayPartTargeting(); - $targeting->setDaysOfWeek(['MONDAY', 'WEDNESDAY', 'FRIDAY']); - $targeting->setHoursOfDay([9, 15, 16]); - $targeting->setUserLocalTime(true); - $template->setDayPartTargeting($targeting); - - $result = $this->service->targetingTemplates->insert( - $values['user_profile_id'], - $template - ); - - $this->printResultsTable('Targeting template created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create Targeting Template'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Template ID', - 'name' => 'Template Name']; - } -} diff --git a/php/v3.5/examples/TargetingTemplates/GetTargetingTemplates.php b/php/v3.5/examples/TargetingTemplates/GetTargetingTemplates.php deleted file mode 100755 index f7051c5..0000000 --- a/php/v3.5/examples/TargetingTemplates/GetTargetingTemplates.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all targeting templates

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('Targeting Templates'); - - do { - // Create and execute the targeting templates list request. - $response = $this->service->targetingTemplates->listTargetingTemplates( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getTargetingTemplates() as $template) { - $this->printResultsTableRow($template); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getTargetingTemplates()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All Targeting Templates'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'Template ID', - 'name' => 'Template Name', - 'advertiserId' => 'Advertiser ID']; - } -} diff --git a/php/v3.5/examples/UserProfiles/GetAllUserProfiles.php b/php/v3.5/examples/UserProfiles/GetAllUserProfiles.php deleted file mode 100755 index 336a53a..0000000 --- a/php/v3.5/examples/UserProfiles/GetAllUserProfiles.php +++ /dev/null @@ -1,64 +0,0 @@ -service->userProfiles->listUserProfiles(); - - print '

Listing of User Profiles associated with your account

'; - - $this->printResultsTable('User Profiles', $result['items']); - } - - /** - * {@inheritdoc} - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All User Profiles'; - } - - /** - * {@inheritdoc} - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['profileId' => 'Profile ID', - 'userName' => 'User Name', - 'accountId' => 'Account ID', - 'accountName' => 'Account Name', - 'subAccountId' => 'Subaccount ID', - 'subAccountName' => 'Subaccount Name']; - } -} diff --git a/php/v3.5/examples/UserRoles/CreateUserRole.php b/php/v3.5/examples/UserRoles/CreateUserRole.php deleted file mode 100755 index fb2a4ff..0000000 --- a/php/v3.5/examples/UserRoles/CreateUserRole.php +++ /dev/null @@ -1,106 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true], - ['name' => 'parent_user_role_id', - 'display' => 'Parent User Role ID', - 'required' => true], - ['name' => 'subaccount_id', - 'display' => 'Subaccount ID', - 'required' => true], - ['name' => 'permission_one', - 'display' => 'First Permission ID', - 'required' => true], - ['name' => 'permission_two', - 'display' => 'Second Permission ID', - 'required' => true], - ['name' => 'user_role_name', - 'display' => 'User Role Name', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - printf( - '

Creating user role with name "%s" under parent role ID %s

', - $values['user_role_name'], - $values['parent_user_role_id'] - ); - - $userRole = new Google_Service_Dfareporting_UserRole(); - $userRole->setName($values['user_role_name']); - $userRole->setParentUserRoleId($values['parent_user_role_id']); - $userRole->setPermissions( - [$values['permission_one'], $values['permission_two']] - ); - $userRole->setSubaccountId($values['subaccount_id']); - - $result = $this->service->userRoles->insert( - $values['user_profile_id'], - $userRole - ); - - $this->printResultsTable('User role created.', [$result]); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Create User Role'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'User Role ID', - 'name' => 'User Role Name']; - } -} diff --git a/php/v3.5/examples/UserRoles/GetUserRoles.php b/php/v3.5/examples/UserRoles/GetUserRoles.php deleted file mode 100755 index c7ecece..0000000 --- a/php/v3.5/examples/UserRoles/GetUserRoles.php +++ /dev/null @@ -1,93 +0,0 @@ - 'user_profile_id', - 'display' => 'User Profile ID', - 'required' => true]]; - } - - /** - * (non-PHPdoc) - * @see BaseExample::run() - */ - public function run() - { - $values = $this->formValues; - - print '

Listing all user roles

'; - - $response = null; - $pageToken = null; - - $this->printResultsTableHeader('User Roles'); - - do { - // Create and execute the subaccounts list request. - $response = $this->service->userRoles->listUserRoles( - $values['user_profile_id'], - ['pageToken' => $pageToken] - ); - - foreach ($response->getUserRoles() as $userRoles) { - $this->printResultsTableRow($userRoles); - } - - // Update the next page token. - $pageToken = $response->getNextPageToken(); - } while (!empty($response->getUserRoles()) && !empty($pageToken)); - - $this->printResultsTableFooter(); - } - - /** - * (non-PHPdoc) - * @see BaseExample::getName() - * @return string - */ - public function getName() - { - return 'Get All User Roles'; - } - - /** - * (non-PHPdoc) - * @see BaseExample::getResultsTableHeaders() - * @return array - */ - public function getResultsTableHeaders() - { - return ['id' => 'User Role ID', - 'name' => 'User Role Name']; - } -} diff --git a/php/v3.5/htmlHelper.php b/php/v3.5/htmlHelper.php deleted file mode 100755 index 8bf2486..0000000 --- a/php/v3.5/htmlHelper.php +++ /dev/null @@ -1,81 +0,0 @@ -'; - print ''; - printf('%s', $htmlTitle); - print ''; - print ''; -} - -/** - * Closes the HTML. - */ -function printHtmlFooter() -{ - print ''; - print ''; -} - -/** - * Closes the HTML for samples. - */ -function printSampleHtmlFooter() -{ - print '
Go back to samples list'; - printHtmlFooter(); -} - -/** - * Prints the index with links to the examples. - * @param array $actions supported actions - */ -function printExamplesIndex($actions) -{ - print '

Select a sample from the list

'; - print ''; -} diff --git a/php/v3.5/index.php b/php/v3.5/index.php deleted file mode 100755 index d59533f..0000000 --- a/php/v3.5/index.php +++ /dev/null @@ -1,201 +0,0 @@ -setApplicationName( - 'DCM/DFA Reporting and Trafficking API PHP Samples' -); -$client->addScope(Google_Service_Dfareporting::DFAREPORTING); -$client->addScope(Google_Service_Dfareporting::DFATRAFFICKING); -$client->addScope(Google_Service_Dfareporting::DDMCONVERSIONS); -$client->setAccessType('offline'); - -if (getenv('GOOGLE_APPLICATION_CREDENTIALS')) { - $client->useApplicationDefaultCredentials(); -} else { - // Be sure to replace the contents of client_secrets.json with your developer - // credentials. - $client->setAuthConfigFile('client_secrets.json'); -} - -// Create service. -$service = new Google_Service_Dfareporting($client); - -// If we're logging out we just need to clear our local access token. -// Note that this only logs you out of the session. If STORE_ON_DISK is -// enabled and you want to remove stored data, delete the file. -if (isset($_REQUEST['logout'])) { - unset($_SESSION['access_token']); -} - -// If we have a code back from the OAuth 2.0 flow, we need to exchange that -// with the authenticate() function. We store the resultant access token -// bundle in the session (and disk, if enabled), and redirect to this page. -if (isset($_GET['code'])) { - $client->authenticate($_GET['code']); - // Note that "getAccessToken" actually retrieves both the access and refresh - // tokens, assuming both are available. - $_SESSION['access_token'] = $client->getAccessToken(); - if (STORE_ON_DISK) { - file_put_contents(TOKEN_FILENAME, json_encode($_SESSION['access_token'])); - } - $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; - header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); - exit; -} - -// If we have an access token, we can make requests, else we generate an -// authentication URL. -if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { - $client->setAccessToken($_SESSION['access_token']); -} elseif (STORE_ON_DISK && file_exists(TOKEN_FILENAME) && - filesize(TOKEN_FILENAME) > 0) { - // Note that "setAccessToken" actually sets both the access and refresh token, - // assuming both were saved. - $client->setAccessToken(file_get_contents(TOKEN_FILENAME)); - $_SESSION['access_token'] = $client->getAccessToken(); -} else { - // If we're doing disk storage, generate a URL that forces user approval. - // This is the only way to guarantee we get back a refresh token. - if (STORE_ON_DISK) { - $client->setApprovalPrompt('force'); - } - $authUrl = $client->createAuthUrl(); -} - -$pageTitle = sprintf( - 'DCM/DFA Reporting and Trafficking API %s PHP usage samples', - $service->version -); -printHtmlHeader($pageTitle); - -if (isset($authUrl)) { - // No access token found, show the link to generate one - printf("", $authUrl); -} else { - print "Logout"; -} - -if ($client->getAccessToken()) { - // If the action is set, dispatch the action if supported - if (isset($_GET['action'])) { - $action = decodeActionString($_GET['action']); - if (!isValidAction($action)) { - die('Unsupported action: ' . $_GET['action'] . "\n"); - } - - displayAction($action); - } else { - // Show the list of links to supported actions. - printExamplesIndex(getSupportedActions()); - printHtmlFooter(); - } - - // Note that we re-store the access_token bundle, just in case anything - // changed during the request - the main thing that might happen here is the - // access token itself is refreshed if the application has offline access. - $_SESSION['access_token'] = $client->getAccessToken(); -} - -/** - * Displays the requested action. - */ -function displayAction($action) -{ - global $service; - - // Render the required action. - include_once 'examples/' . $action[0] . '/' . $action[1] . '.php'; - $class = $action[1]; - $example = new $class($service); - printHtmlHeader($example->getName()); - try { - $example->execute(); - } catch (Google_Exception $ex) { - print_r($ex); - print 'An error as occurred while calling the example:
'; - print $ex->getMessage(); - } - printSampleHtmlFooter(); -} - -/** - * Determines whether the requested action is in our list of supported actions. - */ -function isValidAction($action) -{ - $actions = getSupportedActions(); - - if (array_key_exists($action[0], $actions)) { - $section = $actions[$action[0]]; - if (in_array($action[1], $section)) { - return true; - } - } - - return false; -} - -/** - * Decodes an action string passed as a URL parameter into a section and action - * pair. - */ -function decodeActionString($actionString) -{ - $parts = explode(':', $actionString); - if (count($parts) != 2) { - die('Invalid action specified.'); - } - - return $parts; -} - -/** - * Builds an array containing the supported actions, separated into sections. - */ -function getSupportedActions() -{ - $actions = []; - - foreach (glob('examples/*/*.php') as $file) { - $dir = dirname($file); - $section = substr($dir, strrpos($dir, '/') + 1); - - if (!array_key_exists($section, $actions)) { - $actions[$section] = []; - } - - $actions[$section][] = basename($file, '.php'); - } - - return $actions; -} diff --git a/php/v3.5/styles/style.css b/php/v3.5/styles/style.css deleted file mode 100755 index c64bc3b..0000000 --- a/php/v3.5/styles/style.css +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2015 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -a { - font-size: .9em; - color: black; -} - -table, th, td { - border: 1px solid black; -} - -ul { - list-style: none; -} - -.nav { - padding-left: 0; -} - -.noResults { - font-weight: bold; - text-align: center; -} - diff --git a/python/v3_4/README.md b/python/v3_4/README.md deleted file mode 100644 index be20287..0000000 --- a/python/v3_4/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# DFA Reporting and Trafficking Python Samples - -This is a collection of samples written in Python which provide a starting place -for your experimentation into the DFA Reporting and Trafficking API. - -## Prerequisites - -Please make sure that you're running the latest version of Python 2 and have pip -installed. Use the following command from the samples directory to install all -dependencies: - -```Batchfile -$ pip install --upgrade google-api-python-client -``` - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Running the Examples - -I'm assuming you've checked out the code and are reading this from a local -directory. If not check out the code to a local directory. - -1. Start up a sample, e.g. - - $ python create_report.py - -2. Complete the authorization steps on your browser - -3. Examine your shell output, be inspired and start hacking an amazing new app! diff --git a/python/v3_4/__init__.py b/python/v3_4/__init__.py deleted file mode 100644 index f9fabef..0000000 --- a/python/v3_4/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Code samples for the DCM/DFA Reporting and Trafficking API.""" diff --git a/python/v3_4/assign_advertiser_to_advertiser_group.py b/python/v3_4/assign_advertiser_to_advertiser_group.py deleted file mode 100755 index c9a66fa..0000000 --- a/python/v3_4/assign_advertiser_to_advertiser_group.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example assigns an advertiser to an advertiser group. - -CAUTION: An advertiser that has campaigns associated with it cannot be -removed from an advertiser group once assigned. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add advertiser groups for') -argparser.add_argument( - 'advertiser_group_id', type=int, - help='The ID of the advertiser group to add to') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_group_id = flags.advertiser_group_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - advertiser = { - 'advertiserGroupId': advertiser_group_id - } - - request = service.advertisers().patch( - profileId=profile_id, id=advertiser_id, body=advertiser) - - # Execute request and print response. - response = request.execute() - - print ('Assigned advertiser with ID %s to advertiser group with ID %s.' - % (response['id'], response['advertiserGroupId'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/assign_creative_to_campaign.py b/python/v3_4/assign_creative_to_campaign.py deleted file mode 100755 index 940565e..0000000 --- a/python/v3_4/assign_creative_to_campaign.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example assigns a given creative to a given campaign. - -Note that both the creative and campaign must be associated with the same -advertiser. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to create this association as') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to associate the creative with') -argparser.add_argument( - 'creative_id', type=int, - help='The ID of the creative to be associated') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - creative_id = flags.creative_id - - try: - # Construct the request. - association = { - 'creativeId': creative_id - } - - request = service.campaignCreativeAssociations().insert( - profileId=profile_id, campaignId=campaign_id, body=association) - - # Execute request and print response. - response = request.execute() - - print ('Creative with ID %s is now associated with campaign %s.' - % (response['creativeId'], campaign_id)) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/authenticate_using_service_account.py b/python/v3_4/authenticate_using_service_account.py deleted file mode 100644 index b3cdc5c..0000000 --- a/python/v3_4/authenticate_using_service_account.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example demonstrates how to authenticate using a service account. - -An optional Google account email to impersonate may be specified as follows: - authenticate_using_service_account.py -i - -This optional flag only applies to service accounts which have domain-wide -delegation enabled and wish to make API requests on behalf of an account -within that domain. Using this flag will not allow you to impersonate a -user from a domain you don't own (e.g., gmail.com). -""" - -import argparse -import sys - -from googleapiclient import discovery -import httplib2 -from oauth2client import client -from oauth2client import tools -from oauth2client.service_account import ServiceAccountCredentials - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'path_to_service_account_json_file', - help='Path to the service account JSON file to use for authenticating.') -argparser.add_argument( - '-i', - '--impersonation_email', - help='Google account email to impersonate.') - -# The OAuth 2.0 scopes to request. -OAUTH_SCOPES = ['https://www.googleapis.com/auth/dfareporting'] - - -def main(argv): - # Retrieve command line arguments. - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter, - parents=[tools.argparser, argparser]) - flags = parser.parse_args(argv[1:]) - - # Authenticate using the supplied service account credentials - http = authenticate_using_service_account( - flags.path_to_service_account_json_file, - flags.impersonation_email) - - # Construct a service object via the discovery service. - service = discovery.build('dfareporting', 'v3.4', http=http) - - try: - # Construct the request. - request = service.userProfiles().list() - - # Execute request and print response. - response = request.execute() - - for profile in response['items']: - print('Found user profile with ID %s and user name "%s".' % - (profile['profileId'], profile['userName'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def authenticate_using_service_account(path_to_service_account_json_file, - impersonation_email): - """Authorizes an httplib2.Http instance using service account credentials.""" - # Load the service account credentials from the specified JSON keyfile. - credentials = ServiceAccountCredentials.from_json_keyfile_name( - path_to_service_account_json_file, - scopes=OAUTH_SCOPES) - - # Configure impersonation (if applicable). - if impersonation_email: - credentials = credentials.create_delegated(impersonation_email) - - # Use the credentials to authorize an httplib2.Http instance. - http = credentials.authorize(httplib2.Http()) - - return http - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/authenticate_using_user_account.py b/python/v3_4/authenticate_using_user_account.py deleted file mode 100644 index 891499b..0000000 --- a/python/v3_4/authenticate_using_user_account.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example demonstrates how to authenticate using a user account. - -Utilizes the OAuth 2.0 installed application flow. -""" - -import argparse -import sys - -from googleapiclient import discovery -import httplib2 -from oauth2client import client -from oauth2client import tools -from oauth2client.file import Storage - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'path_to_client_secrets_file', - help='Path to the client_secrets.json file to use for authenticating.') - -# Filename used for the credential store. -CREDENTIAL_STORE_FILE = 'auth-sample.dat' - -# The OAuth 2.0 scopes to request. -OAUTH_SCOPES = ['https://www.googleapis.com/auth/dfareporting'] - - -def main(argv): - # Retrieve command line arguments. - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter, - parents=[tools.argparser, argparser]) - flags = parser.parse_args(argv[1:]) - - # Authenticate using the supplied user account credentials - http = authenticate_using_user_account(flags.path_to_client_secrets_file) - - # Construct a service object via the discovery service. - service = discovery.build('dfareporting', 'v3.4', http=http) - - try: - # Construct the request. - request = service.userProfiles().list() - - # Execute request and print response. - response = request.execute() - - for profile in response['items']: - print('Found user profile with ID %s and user name "%s".' % - (profile['profileId'], profile['userName'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def authenticate_using_user_account(path_to_client_secrets_file): - """Authorizes an httplib2.Http instance using user account credentials.""" - # Set up a Flow object to be used if we need to authenticate. - flow = client.flow_from_clientsecrets( - path_to_client_secrets_file, scope=OAUTH_SCOPES) - - # Check whether credentials exist in the credential store. Using a credential - # store allows auth credentials to be cached, so they survive multiple runs - # of the application. This avoids prompting the user for authorization every - # time the access token expires, by remembering the refresh token. - storage = Storage(CREDENTIAL_STORE_FILE) - credentials = storage.get() - - # If no credentials were found, go through the authorization process and - # persist credentials to the credential store. - if credentials is None or credentials.invalid: - credentials = tools.run_flow(flow, storage, - tools.argparser.parse_known_args()[0]) - - # Use the credentials to authorize an httplib2.Http instance. - http = credentials.authorize(httplib2.Http()) - - return http - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/client_secrets.json b/python/v3_4/client_secrets.json deleted file mode 100644 index f9cf7ff..0000000 --- a/python/v3_4/client_secrets.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "installed": { - "client_id": "[[INSERT CLIENT ID HERE]]", - "client_secret": "[[INSERT CLIENT SECRET HERE]]", - "redirect_uris": [], - "auth_uri": "https://accounts.google.com/o/oauth2/auth", - "token_uri": "https://accounts.google.com/o/oauth2/token" - } -} \ No newline at end of file diff --git a/python/v3_4/configure_dynamic_asset_selection.py b/python/v3_4/configure_dynamic_asset_selection.py deleted file mode 100644 index 5c3ec29..0000000 --- a/python/v3_4/configure_dynamic_asset_selection.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example enables dynamic asset selection for an in-stream video creative. - -Requires an existing in-stream video creative, a new video asset, and a -targeting template ID as input. To get an in-stream video creative, run -create_instream_video_creative.py. To get a targeting template, run -create_targeting_template.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to configure dynamic asset selection for') -argparser.add_argument( - 'creative_id', type=int, - help='The ID of the in-stream video creative to configure selection for.') -argparser.add_argument( - 'template_id', type=int, - help='The ID of the template to use for targeting.') -argparser.add_argument( - 'video_name', help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_video_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - creative_id = flags.creative_id - template_id = flags.template_id - path_to_video_file = flags.path_to_video_file - video_name = flags.video_name - - try: - # Retrieve the specified creative. - creative = service.creatives().get(profileId=profile_id, - id=creative_id).execute() - - if not creative or creative['type'] != 'INSTREAM_VIDEO': - sys.exit('Invalid creative specified.') - - if 'creativeAssetSelection' not in creative: - # Locate an existing video asset to use as a default. - default_asset_id = next((asset['id'] - for asset in creative['creativeAssets'] - if asset['role'] == 'PARENT_VIDEO'), None) - - if not default_asset_id: - sys.exit('Default video asset could not be found.') - - # Enable dynamic asset selection for the creative. - creative['dynamicAssetSelection'] = True - - # Create a new selection using the existing asset as a default. - creative['creativeAssetSelection'] = { - 'defaultAssetId': default_asset_id, - 'rules': [] - } - - # Upload the new video asset and add it to the creative. - video_asset = upload_creative_asset( - service, profile_id, creative['advertiserId'], video_name, - path_to_video_file, 'VIDEO') - - creative['creativeAssets'].append({ - 'assetIdentifier': video_asset['assetIdentifier'], - 'role': 'PARENT_VIDEO' - }) - - # Create a rule targeting the new video asset and add it to the creative. - creative['creativeAssetSelection']['rules'].append({ - 'assetId': video_asset['id'], - 'name': 'Test rule for asset %s' % video_asset['id'], - 'targetingTemplateId': template_id - }) - - request = service.creatives().update(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Dynamic asset selection enabled for creative with ID %s.' - % response['id']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns a creative asset metadata object.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_advertiser.py b/python/v3_4/create_advertiser.py deleted file mode 100755 index f396e99..0000000 --- a/python/v3_4/create_advertiser.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an advertiser in a given DFA account.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add an advertiser for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save advertiser. - advertiser = { - 'name': 'Test Advertiser', - 'status': 'APPROVED' - } - - request = service.advertisers().insert( - profileId=profile_id, body=advertiser) - - # Execute request and print response. - response = request.execute() - - print ('Created advertiser with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_advertiser_group.py b/python/v3_4/create_advertiser_group.py deleted file mode 100755 index 02a1edd..0000000 --- a/python/v3_4/create_advertiser_group.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an advertiser group.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add an advertiser group for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save advertiser. - advertiser_group = { - 'name': 'Test Advertiser Group' - } - - request = service.advertiserGroups().insert( - profileId=profile_id, body=advertiser_group) - - # Execute request and print response. - response = request.execute() - - print ('Created advertiser group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_advertiser_landing_page.py b/python/v3_4/create_advertiser_landing_page.py deleted file mode 100755 index aab6db9..0000000 --- a/python/v3_4/create_advertiser_landing_page.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an advertiser landing page.""" - -import argparse -import sys -import uuid - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to add an advertiser landing page for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to associate the landing page with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct a landing page object. - landing_page = { - 'name': 'Test Landing Page #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'archived': 'false', - 'url': 'https://www.google.com' - } - - request = service.advertiserLandingPages().insert( - profileId=profile_id, body=landing_page) - - # Execute request and print response. - response = request.execute() - - print('Created advertiser landing page with ID %s and name "%s".' % - (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_campaign.py b/python/v3_4/create_campaign.py deleted file mode 100755 index a946587..0000000 --- a/python/v3_4/create_campaign.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a campaign in a given advertiser. - -To create an advertiser, run create_advertiser.py. -""" - -import argparse -import sys -import uuid - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a campaign for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to associate the campaign with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Construct and save campaign. - campaign = { - 'name': 'Test Campaign #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'archived': 'false', - 'defaultLandingPageId': default_landing_page['id'], - 'startDate': '2015-01-01', - 'endDate': '2020-01-01' - } - - request = service.campaigns().insert(profileId=profile_id, body=campaign) - - # Execute request and print response. - response = request.execute() - - print('Created campaign with ID %s and name "%s".' % (response['id'], - response['name'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def get_advertiser_landing_page(service, profile_id, advertiser_id): - # Retrieve a single landing page from the specified advertiser. - response = service.advertiserLandingPages().list( - profileId=profile_id, advertiserIds=[advertiser_id], - maxResults=1).execute() - - if not response['landingPages']: - sys.exit( - 'No landing pages found for advertiser with ID %d.' % advertiser_id) - - return response['landingPages'][0] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_campaign_event_tag.py b/python/v3_4/create_campaign_event_tag.py deleted file mode 100755 index 4d061de..0000000 --- a/python/v3_4/create_campaign_event_tag.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an event tag for the specified campaign.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add an event tag for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to add an event tag for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - - try: - # Construct and save event tag. - event_tag = { - 'campaignId': campaign_id, - 'name': 'Test Campaign Event Tag', - 'status': 'ENABLED', - 'type': 'CLICK_THROUGH_EVENT_TAG', - 'url': 'https://www.google.com' - } - - request = service.eventTags().insert(profileId=profile_id, body=event_tag) - - # Execute request and print response. - response = request.execute() - - print ('Created campaign event tag with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_content_category.py b/python/v3_4/create_content_category.py deleted file mode 100755 index c13ccfd..0000000 --- a/python/v3_4/create_content_category.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a content category with given name and description.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a content category for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save content category. - content_category = { - 'name': 'Test Category' - } - - request = service.contentCategories().insert( - profileId=profile_id, body=content_category) - - # Execute request and print response. - response = request.execute() - - print ('Created content category with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_creative_field.py b/python/v3_4/create_creative_field.py deleted file mode 100644 index 1f3655e..0000000 --- a/python/v3_4/create_creative_field.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a creative field associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a creative field for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a creative field for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct and save creative field - creative_field = { - 'advertiserId': advertiser_id, - 'name': 'Test Creative Field' - } - - request = service.creativeFields().insert( - profileId=profile_id, body=creative_field) - - # Execute request and print response. - response = request.execute() - - print ('Created creative field with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_creative_field_value.py b/python/v3_4/create_creative_field_value.py deleted file mode 100644 index 21413a4..0000000 --- a/python/v3_4/create_creative_field_value.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a creative field value for a given creative field. - -To get the creative field ID, run get_creative_fields.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a creative field value for') -argparser.add_argument( - 'field_id', type=int, - help='The ID of the creative field to add a value for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - field_id = flags.field_id - - try: - # Construct and save creative field value - field_value = { - 'value': 'Test Creative Field Value' - } - - request = service.creativeFieldValues().insert( - profileId=profile_id, creativeFieldId=field_id, body=field_value) - - # Execute request and print response. - response = request.execute() - - print ('Created creative field value with ID %s and value "%s".' - % (response['id'], response['value'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_creative_group.py b/python/v3_4/create_creative_group.py deleted file mode 100644 index c852e1e..0000000 --- a/python/v3_4/create_creative_group.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a creative group associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. Valid group numbers are -limited to 1 or 2. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a creative group for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a creative group for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct and save creative group - creative_group = { - 'advertiserId': advertiser_id, - 'groupNumber': 1, - 'name': 'Test Creative Group' - } - - request = service.creativeGroups().insert( - profileId=profile_id, body=creative_group) - - # Execute request and print response. - response = request.execute() - - print ('Created creative group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_display_image_gallery_creative.py b/python/v3_4/create_display_image_gallery_creative.py deleted file mode 100755 index 624a9ab..0000000 --- a/python/v3_4/create_display_image_gallery_creative.py +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a display image gallery creative. - -Requires two image assets and an advertiser ID as input. To get an advertiser -ID, run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'size_id', type=int, - help='The ID of the size of this creative.') -argparser.add_argument( - 'image1_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_image1_file', - help='Path to the asset file to be uploaded.') -argparser.add_argument( - 'image2_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_image2_file', - help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - image1_name = flags.image1_name - image2_name = flags.image2_name - path_to_image1_file = flags.path_to_image1_file - path_to_image2_file = flags.path_to_image2_file - size_id = flags.size_id - - try: - # Upload the first image asset - image1_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, image1_name, path_to_image1_file, - 'HTML_IMAGE') - - # Upload the second image asset - image2_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, image2_name, path_to_image2_file, - 'HTML_IMAGE') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'autoAdvanceImages': True, - 'clickTags': [ - {'eventName': image1_asset_id['name'], - 'name': image1_asset_id['name']}, - {'eventName': image2_asset_id['name'], - 'name': image2_asset_id['name']} - ], - 'creativeAssets': [ - {'assetIdentifier': image1_asset_id, 'role': 'PRIMARY'}, - {'assetIdentifier': image2_asset_id, 'role': 'PRIMARY'}, - ], - 'name': 'Test display image gallery creative', - 'size': {'id': size_id}, - 'type': 'DISPLAY_IMAGE_GALLERY' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created display image gallery creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_display_redirect_creative.py b/python/v3_4/create_display_redirect_creative.py deleted file mode 100755 index 3f2c7b8..0000000 --- a/python/v3_4/create_display_redirect_creative.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a display redirect creative. - -To get a size ID, run get_size.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'image_url', - help='URL of the image to associate with this creative.') -argparser.add_argument( - 'size_id', type=int, - help='The ID of the size of the specified image.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - image_url = flags.image_url - size_id = flags.size_id - - try: - # Construct the basic creative structure. - creative = { - 'advertiserId': advertiser_id, - 'name': 'Test display redirect creative', - 'redirect_url': image_url, - 'size': {'id': size_id}, - 'type': 'DISPLAY_REDIRECT' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created display redirect creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_floodlight_activity.py b/python/v3_4/create_floodlight_activity.py deleted file mode 100755 index db11f5e..0000000 --- a/python/v3_4/create_floodlight_activity.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a floodlight activity in a given activity group. - -To create an activity group, run create_floodlight_activity_group.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'activity_group_id', type=int, - help='The ID of the floodlight activity group to create an activity for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - activity_group_id = flags.activity_group_id - - try: - # Construct and save floodlight activity. - floodlight_activity = { - 'countingMethod': 'STANDARD_COUNTING', - 'expectedUrl': 'http://www.google.com', - 'floodlightActivityGroupId': activity_group_id, - 'floodlightTagType': 'GLOBAL_SITE_TAG', - 'name': 'Test Floodlight Activity' - } - - request = service.floodlightActivities().insert( - profileId=profile_id, body=floodlight_activity) - - # Execute request and print response. - response = request.execute() - - print ('Created floodlight activity with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_floodlight_activity_group.py b/python/v3_4/create_floodlight_activity_group.py deleted file mode 100755 index 7075be8..0000000 --- a/python/v3_4/create_floodlight_activity_group.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a new activity group for a floodlight configuration. - -To get a floodlight configuration ID, run get_advertisers.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'floodlight_config_id', type=int, - help='The ID of the floodlight config to create a group for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - floodlight_config_id = flags.floodlight_config_id - - try: - # Construct and save floodlight activity group. - activity_group = { - 'name': 'Test Floodlight Activity Group', - 'floodlightConfigurationId': floodlight_config_id, - 'type': 'COUNTER' - } - - request = service.floodlightActivityGroups().insert( - profileId=profile_id, body=activity_group) - - # Execute request and print response. - response = request.execute() - - print ('Created floodlight activity group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_html5_display_creative.py b/python/v3_4/create_html5_display_creative.py deleted file mode 100755 index f3ab214..0000000 --- a/python/v3_4/create_html5_display_creative.py +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an HTML5 display creative. - -Requires an HTML5 asset, backup image asset, and an advertiser ID as input. -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'size_id', type=int, help='The ID of the size of this creative.') -argparser.add_argument( - 'html5_asset_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_html5_asset_file', help='Path to the asset file to be uploaded.') -argparser.add_argument( - 'backup_image_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_backup_image_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - backup_image_name = flags.backup_image_name - html5_asset_name = flags.html5_asset_name - path_to_backup_image_file = flags.path_to_backup_image_file - path_to_html5_asset_file = flags.path_to_html5_asset_file - size_id = flags.size_id - - try: - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Upload the HTML5 asset - html5_asset_id = upload_creative_asset(service, profile_id, advertiser_id, - html5_asset_name, - path_to_html5_asset_file, 'HTML') - - # Upload the backup image asset - backup_image_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, backup_image_name, - path_to_backup_image_file, 'HTML_IMAGE') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'backupImageClickThroughUrl': { - 'landingPageId': default_landing_page['id'] - }, - 'backupImageReportingLabel': 'backup_image_exit', - 'backupImageTargetWindow': {'targetWindowOption': 'NEW_WINDOW'}, - 'clickTags': [{ - 'eventName': 'exit', - 'name': 'click_tag', - 'clickThroughUrl': {'landingPageId': default_landing_page['id']} - }], - 'creativeAssets': [ - {'assetIdentifier': html5_asset_id, 'role': 'PRIMARY'}, - {'assetIdentifier': backup_image_asset_id, 'role': 'BACKUP_IMAGE'} - ], - 'name': 'Test HTML5 display creative', - 'size': {'id': size_id}, - 'type': 'DISPLAY' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print('Created HTML5 display creative with ID %s and name "%s".' % - (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def get_advertiser_landing_page(service, profile_id, advertiser_id): - # Retrieve a single landing page from the specified advertiser. - response = service.advertiserLandingPages().list( - profileId=profile_id, advertiserIds=[advertiser_id], - maxResults=1).execute() - - if not response['landingPages']: - sys.exit( - 'No landing pages found for advertiser with ID %d.' % advertiser_id) - - return response['landingPages'][0] - - -def upload_creative_asset(service, profile_id, advertiser_id, asset_name, - path_to_asset_file, asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = {'assetIdentifier': {'name': asset_name, 'type': asset_type}} - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_image_display_creative.py b/python/v3_4/create_image_display_creative.py deleted file mode 100755 index dd5ec44..0000000 --- a/python/v3_4/create_image_display_creative.py +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an image display creative. - -Requires an image asset and advertiser ID as input. To get an advertiser ID, -run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'size_id', type=int, - help='The ID of the size of this creative.') -argparser.add_argument( - 'image_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_image_file', - help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - image_name = flags.image_name - path_to_image_file = flags.path_to_image_file - size_id = flags.size_id - - try: - # Upload the creative asset - creative_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, image_name, path_to_image_file, - 'HTML_IMAGE') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'creativeAssets': [ - {'assetIdentifier': creative_asset_id, 'role': 'PRIMARY'} - ], - 'name': 'Test image display creative', - 'size': {'id': size_id}, - 'type': 'DISPLAY' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created image display creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_instream_audio_creative.py b/python/v3_4/create_instream_audio_creative.py deleted file mode 100755 index 5c996c1..0000000 --- a/python/v3_4/create_instream_audio_creative.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an in-stream audio creative. - -Requires an audio asset and advertiser ID as input. To get an advertiser ID, -run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'audio_name', help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_audio_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - path_to_audio_file = flags.path_to_audio_file - audio_name = flags.audio_name - - try: - # Upload the creative asset - creative_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, audio_name, path_to_audio_file, - 'AUDIO') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'creativeAssets': [ - {'assetIdentifier': creative_asset_id, 'role': 'PARENT_AUDIO'} - ], - 'name': 'Test in-stream audio creative', - 'type': 'INSTREAM_AUDIO' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created in-stream audio creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_instream_video_creative.py b/python/v3_4/create_instream_video_creative.py deleted file mode 100755 index 4cc64af..0000000 --- a/python/v3_4/create_instream_video_creative.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an in-stream video creative. - -Requires a video asset and advertiser ID as input. To get an advertiser ID, -run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'video_name', help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_video_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - path_to_video_file = flags.path_to_video_file - video_name = flags.video_name - - try: - # Upload the creative asset - creative_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, video_name, path_to_video_file, - 'VIDEO') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'creativeAssets': [ - {'assetIdentifier': creative_asset_id, 'role': 'PARENT_VIDEO'} - ], - 'name': 'Test in-stream video creative', - 'type': 'INSTREAM_VIDEO' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created in-stream video creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_placement.py b/python/v3_4/create_placement.py deleted file mode 100755 index 762ed6e..0000000 --- a/python/v3_4/create_placement.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an agency paid regular placement in a given campaign. - -Requires the DFA site ID and campaign ID in which the placement will be created -into. To create a campaign, run create_campaign.py. To get DFA site ID, run -get_site.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to associate the placement with') -argparser.add_argument( - 'site_id', type=int, - help='The ID of the site to associate the placement with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - site_id = flags.site_id - - try: - # Look up the campaign - campaign = service.campaigns().get( - profileId=profile_id, id=campaign_id).execute() - - # Construct and save placement. - placement = { - 'name': 'Test Placement', - 'campaignId': campaign_id, - 'compatibility': 'DISPLAY', - 'siteId': site_id, - 'size': { - 'height': '1', - 'width': '1' - }, - 'paymentSource': 'PLACEMENT_AGENCY_PAID', - 'tagFormats': ['PLACEMENT_TAG_STANDARD'] - } - - # Set the pricing schedule for the placement. - placement['pricingSchedule'] = { - 'startDate': campaign['startDate'], - 'endDate': campaign['endDate'], - 'pricingType': 'PRICING_TYPE_CPM' - } - - request = service.placements().insert(profileId=profile_id, body=placement) - - # Execute request and print response. - response = request.execute() - - print ('Created placement with ID %s and name "%s".' - % (long(response['id']), response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_placement_group.py b/python/v3_4/create_placement_group.py deleted file mode 100755 index 4103571..0000000 --- a/python/v3_4/create_placement_group.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a placement group in a given campaign. - -Requires the DFA site ID and campaign ID in which the placement group will be -created into. To create a campaign, run create_campaign.py. To get DFA site ID, -run get_site.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement group for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to associate the placement group with') -argparser.add_argument( - 'site_id', type=int, - help='The ID of the site to associate the placement group with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - site_id = flags.site_id - - try: - # Look up the campaign - campaign = service.campaigns().get( - profileId=profile_id, id=campaign_id).execute() - - # Construct and save placement. - placement_group = { - 'name': 'Test Placement Group', - 'campaignId': campaign_id, - 'siteId': site_id, - 'placementGroupType': 'PLACEMENT_PACKAGE', - 'pricingSchedule': { - 'startDate': campaign['startDate'], - 'endDate': campaign['endDate'], - 'pricingType': 'PRICING_TYPE_CPM' - } - } - - request = service.placementGroups().insert( - profileId=profile_id, body=placement_group) - - # Execute request and print response. - response = request.execute() - - print ('Created placement group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_placement_strategy.py b/python/v3_4/create_placement_strategy.py deleted file mode 100755 index d5c8bf5..0000000 --- a/python/v3_4/create_placement_strategy.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a placement strategy with the given name.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement strategy for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save placement strategy. - placement_strategy = { - 'name': 'Test Strategy' - } - - request = service.placementStrategies().insert( - profileId=profile_id, body=placement_strategy) - - # Execute request and print response. - response = request.execute() - - print ('Created placement strategy with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_remarketing_list.py b/python/v3_4/create_remarketing_list.py deleted file mode 100644 index 644b401..0000000 --- a/python/v3_4/create_remarketing_list.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Creates a remarketing list for a given advertiser and floodlight activity. - -Note: this sample assumes that the floodlight activity specified has a U1 custom -floodlight variable. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a remarketing list for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a remarketing list for') -argparser.add_argument( - 'activity_id', type=int, - help='The ID of the floodlight activity to add a remarketing list for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - activity_id = flags.activity_id - - try: - # Create a list population term. - # This term matches all visitors with a U1 value exactly matching - # "test_value" - term = { - 'operator': 'STRING_EQUALS', - 'type': 'CUSTOM_VARIABLE_TERM', - 'value': 'test_value', - 'variableName': 'U1' - } - - # Add the term to a clause and the clause to a population rule. - # This rule will target all visitors who trigger the specified floodlight - # activity and satisfy the custom rule defined in the list population term. - rule = { - 'floodlightActivityId': activity_id, - 'listPopulationClauses': {'terms': [term]} - } - - # Create the remarketing list. - remarketing_list = { - 'name': 'Test Remarketing List', - 'active': 'true', - 'advertiserId': advertiser_id, - 'lifeSpan': 30, - 'listPopulationRule': rule - } - - request = service.remarketingLists().insert( - profileId=profile_id, body=remarketing_list) - - # Execute request and print response. - response = request.execute() - - print ('Created remarketing list with ID %s and name "%s."' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_report.py b/python/v3_4/create_report.py deleted file mode 100644 index e51aaa1..0000000 --- a/python/v3_4/create_report.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the 'License'); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""An end-to-end example of how to create and configure a standard report.""" - -import argparse -from datetime import date -from datetime import timedelta -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to create a report for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # 1. Create a report resource. - report = create_report_resource() - - # 2. Define the report criteria. - define_report_criteria(report) - - # 3. (optional) Look up compatible fields. - find_compatible_fields(service, profile_id, report) - - # 4. Add dimension filters to the report criteria. - add_dimension_filters(service, profile_id, report) - - # 5. Save the report resource. - report = insert_report_resource(service, profile_id, report) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def create_report_resource(): - """Creates a report resource.""" - report = { - # Set the required fields "name" and "type". - 'name': 'Example Standard Report', - 'type': 'STANDARD', - # Set optional fields. - 'fileName': 'example_report', - 'format': 'CSV' - } - - print 'Creating %s report resource with name "%s".' % (report['type'], - report['name']) - - return report - - -def define_report_criteria(report): - """Defines a criteria for the report.""" - # Define a date range to report on. This example uses explicit start and end - # dates to mimic the "LAST_30_DAYS" relative date range. - end_date = date.today() - start_date = end_date - timedelta(days=30) - - # Create a report criteria. - criteria = { - 'dateRange': { - 'startDate': start_date.strftime('%Y-%m-%d'), - 'endDate': end_date.strftime('%Y-%m-%d') - }, - 'dimensions': [{ - 'name': 'advertiser' - }], - 'metricNames': ['clicks', 'impressions'] - } - - # Add the criteria to the report resource. - report['criteria'] = criteria - - print '\nAdded report criteria:\n%s' % criteria - - -def find_compatible_fields(service, profile_id, report): - """Finds and adds a compatible dimension/metric to the report.""" - fields = service.reports().compatibleFields().query( - profileId=profile_id, body=report).execute() - - report_fields = fields['reportCompatibleFields'] - - if report_fields['dimensions']: - # Add a compatible dimension to the report. - report['criteria']['dimensions'].append({ - 'name': report_fields['dimensions'][0]['name'] - }) - elif report_fields['metrics']: - # Add a compatible metric to the report. - report['criteria']['metricNames'].append( - report_fields['metrics'][0]['name']) - - print('\nUpdated report criteria (with compatible fields):\n%s' % - report['criteria']) - - -def add_dimension_filters(service, profile_id, report): - """Finds and adds a valid dimension filter to the report.""" - # Query advertiser dimension values for report run dates. - request = { - 'dimensionName': 'advertiser', - 'endDate': report['criteria']['dateRange']['endDate'], - 'startDate': report['criteria']['dateRange']['startDate'] - } - - values = service.dimensionValues().query( - profileId=profile_id, body=request).execute() - - if values['items']: - # Add a value as a filter to the report criteria. - report['criteria']['dimensionFilters'] = [values['items'][0]] - - print('\nUpdated report criteria (with valid dimension filters):\n%s' % - report['criteria']) - - -def insert_report_resource(service, profile_id, report): - """Inserts the report.""" - inserted_report = service.reports().insert( - profileId=profile_id, body=report).execute() - - print('\nSuccessfully inserted new report with ID %s.' % - inserted_report['id']) - - return inserted_report - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_rotation_group.py b/python/v3_4/create_rotation_group.py deleted file mode 100644 index 8286711..0000000 --- a/python/v3_4/create_rotation_group.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a rotation group ad in a given campaign.""" - -import argparse -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a rotation group for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to add a rotation group for') -argparser.add_argument( - 'placement_id', type=int, - help='The ID of the placement to add a rotation group for') -argparser.add_argument( - 'creative_id', type=int, - help='The ID of the creative to add to the rotation group') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - placement_id = flags.placement_id - creative_id = flags.creative_id - - try: - # Retrieve the campaign (to get end date). - campaign = service.campaigns().get( - profileId=profile_id, id=campaign_id).execute() - - # Construct creative assignment. - creative_assignment = { - 'active': 'true', - 'creativeId': creative_id, - 'clickThroughUrl': { - 'defaultLandingPage': 'true' - } - } - - # Construct placement assignment. - placement_assignment = { - 'active': 'true', - 'placementId': placement_id, - } - - # Construct creative rotation. - creative_rotation = { - 'creativeAssignments': [creative_assignment], - 'type': 'CREATIVE_ROTATION_TYPE_RANDOM', - 'weightCalculationStrategy': 'WEIGHT_STRATEGY_OPTIMIZED' - } - - # Construct delivery schedule. - delivery_schedule = { - 'impressionRatio': '1', - 'priority': 'AD_PRIORITY_01' - } - - # Construct and save ad. - ad = { - 'active': 'true', - 'campaignId': campaign_id, - 'creativeRotation': creative_rotation, - 'deliverySchedule': delivery_schedule, - 'endTime': '%sT00:00:00Z' % campaign['endDate'], - 'name': 'Test Rotation Group', - 'placementAssignments': [placement_assignment], - 'startTime': '%sT23:59:59Z' % time.strftime('%Y-%m-%d'), - 'type': 'AD_SERVING_STANDARD_AD' - } - - request = service.ads().insert(profileId=profile_id, body=ad) - - # Execute request and print response. - response = request.execute() - - print ('Created rotation group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_subaccount.py b/python/v3_4/create_subaccount.py deleted file mode 100755 index c463c68..0000000 --- a/python/v3_4/create_subaccount.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a subaccount in a given DFA account. - -To get the account ID, run get_all_userprofiles.py. To get the available -permissions, run get_user_role_permissions.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a subaccount for') -argparser.add_argument( - 'account_id', type=int, - help='The ID of the account to create a subaccount for') -argparser.add_argument( - 'permission_id', type=int, - help='The ID of the permission to apply to this subaccount') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - account_id = flags.account_id - permission_id = flags.permission_id - - try: - # Construct the basic subaccount structure. - subaccount = { - 'name': 'Test Subaccount', - 'accountId': account_id, - 'availablePermissionIds': [permission_id] - } - - request = service.subaccounts().insert( - profileId=profile_id, body=subaccount) - - # Execute request and print response. - response = request.execute() - - print ('Created subaccount with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_targeting_template.py b/python/v3_4/create_targeting_template.py deleted file mode 100644 index 16901c1..0000000 --- a/python/v3_4/create_targeting_template.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a targeting template associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys -import uuid - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a targeting template for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a targeting template for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct a basic targeting template. - # This template will be configured to serve ads on Monday, Wednesday, and - # Friday from 9-10am and 3-5pm. - # Note: targeting template names must be unique within an advetiser. - targeting_template = { - 'advertiserId': advertiser_id, - 'dayPartTargeting': { - 'daysOfWeek': ['MONDAY', 'WEDNESDAY', 'FRIDAY'], - 'hoursOfDay': [9, 15, 16], - 'userLocalTime': True - }, - 'name': 'Test Targeting Template #%s' % uuid.uuid4() - } - - request = service.targetingTemplates().insert(profileId=profile_id, - body=targeting_template) - - # Execute request and print response. - response = request.execute() - - print ('Created targeting template with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_tracking_creative.py b/python/v3_4/create_tracking_creative.py deleted file mode 100755 index 6bbc0a3..0000000 --- a/python/v3_4/create_tracking_creative.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a tracking creative associated with an advertiser.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the basic creative structure. - creative = { - 'advertiserId': advertiser_id, - 'name': 'Test tracking creative', - 'type': 'TRACKING_TEXT' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created tracking creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/create_user_role.py b/python/v3_4/create_user_role.py deleted file mode 100755 index 829cd34..0000000 --- a/python/v3_4/create_user_role.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a user role in a given DFA account. - -To get the account ID, run get_all_userprofiles.py. To get the parent user role -ID, run get_user_roles.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'account_id', type=int, - help='The ID of the subaccount to create a user role for') -argparser.add_argument( - 'parent_role_id', type=int, - help='The ID of the parent user role to assign to this user role') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - account_id = flags.account_id - parent_role_id = flags.parent_role_id - - try: - # Construct the basic user role structure. - user_role = { - 'name': 'Test User Role', - 'accountId': account_id, - 'parentUserRoleId': parent_role_id - } - - request = service.userRoles().insert(profileId=profile_id, body=user_role) - - # Execute request and print response. - response = request.execute() - - print ('Created user role with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/delete_report.py b/python/v3_4/delete_report.py deleted file mode 100644 index 4f615b8..0000000 --- a/python/v3_4/delete_report.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to delete a report.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to delete a report for') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to delete') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Construct the request. - request = service.reports().delete(profileId=profile_id, reportId=report_id) - - # Execute request and print response. - request.execute() - - print 'Successfully deleted report with ID %s.' % report_id - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/dfareporting_utils.py b/python/v3_4/dfareporting_utils.py deleted file mode 100644 index 070971b..0000000 --- a/python/v3_4/dfareporting_utils.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Handles common tasks across all API samples.""" - -import argparse -import os - -from googleapiclient import discovery -import httplib2 -from oauth2client import client -from oauth2client import file as oauthFile -from oauth2client import tools - - -API_NAME = 'dfareporting' -API_VERSION = 'v3.4' -API_SCOPES = ['https://www.googleapis.com/auth/dfareporting', - 'https://www.googleapis.com/auth/dfatrafficking', - 'https://www.googleapis.com/auth/ddmconversions'] - -# Filename used for the credential store. -CREDENTIAL_STORE_FILE = API_NAME + '.dat' - - -def get_arguments(argv, desc, parents=None): - """Validates and parses command line arguments. - - Args: - argv: list of strings, the command-line parameters of the application. - desc: string, a description of the sample being executed. - parents: list of argparse.ArgumentParser, additional command-line parsers. - - Returns: - The parsed command-line arguments. - """ - # Include the default oauth2client argparser - parent_parsers = [tools.argparser] - - if parents: - parent_parsers.extend(parents) - - parser = argparse.ArgumentParser( - description=desc, - formatter_class=argparse.RawDescriptionHelpFormatter, - parents=parent_parsers) - return parser.parse_args(argv[1:]) - - -def load_application_default_credentials(): - """Atempts to load application default credentials. - - Returns: - A credential object initialized with application default credentials or None - if none were found. - """ - try: - credentials = client.GoogleCredentials.get_application_default() - return credentials.create_scoped(API_SCOPES) - except client.ApplicationDefaultCredentialsError: - # No application default credentials, continue to try other options. - pass - - -def load_user_credentials(client_secrets, storage, flags): - """Attempts to load user credentials from the provided client secrets file. - - Args: - client_secrets: path to the file containing client secrets. - storage: the data store to use for caching credential information. - flags: command-line flags. - - Returns: - A credential object initialized with user account credentials. - """ - # Set up a Flow object to be used if we need to authenticate. - flow = client.flow_from_clientsecrets( - client_secrets, - scope=API_SCOPES, - message=tools.message_if_missing(client_secrets)) - - # Retrieve credentials from storage. - # If the credentials don't exist or are invalid run through the installed - # client flow. The storage object will ensure that if successful the good - # credentials will get written back to file. - credentials = storage.get() - if credentials is None or credentials.invalid: - credentials = tools.run_flow(flow, storage, flags) - - return credentials - - -def setup(flags): - """Handles authentication and loading of the API. - - Args: - flags: command-line flags obtained by calling ''get_arguments()''. - - Returns: - An initialized service object. - """ - # Load application default credentials if they're available. - credentials = load_application_default_credentials() - - # Otherwise, load credentials from the provided client secrets file. - if credentials is None: - # Name of a file containing the OAuth 2.0 information for this - # application, including client_id and client_secret, which are found - # on the Credentials tab on the Google Developers Console. - client_secrets = os.path.join(os.path.dirname(__file__), - 'client_secrets.json') - storage = oauthFile.Storage(CREDENTIAL_STORE_FILE) - credentials = load_user_credentials(client_secrets, storage, flags) - - # Authorize HTTP object with the prepared credentials. - http = credentials.authorize(http=httplib2.Http()) - - # Construct and return a service object via the discovery service. - return discovery.build(API_NAME, API_VERSION, http=http) diff --git a/python/v3_4/download_file.py b/python/v3_4/download_file.py deleted file mode 100644 index d529f51..0000000 --- a/python/v3_4/download_file.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to download a report file.""" - -import argparse -import io -import os -import sys - -import dfareporting_utils -from googleapiclient import http -from oauth2client import client - - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to get a file for') -argparser.add_argument( - 'file_id', type=int, - help='The ID of the file to get') - -# Chunk size to use when downloading report files. Defaults to 32MB. -CHUNK_SIZE = 32 * 1024 * 1024 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - report_id = flags.report_id - file_id = flags.file_id - - try: - # Retrieve the file metadata. - report_file = service.files().get(reportId=report_id, - fileId=file_id).execute() - - if report_file['status'] == 'REPORT_AVAILABLE': - # Prepare a local file to download the report contents to. - out_file = io.FileIO(generate_file_name(report_file), mode='wb') - - # Create a get request. - request = service.files().get_media(reportId=report_id, fileId=file_id) - - # Create a media downloader instance. - # Optional: adjust the chunk size used when downloading the file. - downloader = http.MediaIoBaseDownload(out_file, request, - chunksize=CHUNK_SIZE) - - # Execute the get request and download the file. - download_finished = False - while download_finished is False: - _, download_finished = downloader.next_chunk() - - print('File %s downloaded to %s' - % (report_file['id'], os.path.realpath(out_file.name))) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def generate_file_name(report_file): - """Generates a report file name based on the file metadata.""" - # If no filename is specified, use the file ID instead. - file_name = report_file['fileName'] or report_file['id'] - extension = '.csv' if report_file['format'] == 'CSV' else '.xml' - return file_name + extension - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/download_floodlight_tag.py b/python/v3_4/download_floodlight_tag.py deleted file mode 100644 index 835289e..0000000 --- a/python/v3_4/download_floodlight_tag.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example downloads activity tags for a given floodlight activity.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to download tags for') -argparser.add_argument( - 'activity_id', - type=int, - help='The ID of the floodlight activity to download tags for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - activity_id = flags.activity_id - - try: - # Construct the request. - request = service.floodlightActivities().generatetag( - profileId=profile_id, floodlightActivityId=activity_id) - - # Execute request and print response. - response = request.execute() - - if 'globalSiteTagGlobalSnippet' in response: - # Print both global snippet and event snippet. - print('Global site tag global snippet:\n\n%s' % - response['globalSiteTagGlobalSnippet']) - print('\n\nGlobal site tag event snippet:\n\n%s' % - response['floodlightActivityTag']) - else: - # Print the Floodlight activity tag. - print('Floodlight activity tag:\n\n%s' % - response['floodlightActivityTag']) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/download_placement_tags.py b/python/v3_4/download_placement_tags.py deleted file mode 100644 index 57ca8cb..0000000 --- a/python/v3_4/download_placement_tags.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example downloads HTML Tags for a given campaign and placement ID. - -To create campaigns, run create_campaign.py. To create placements, run -create_placement.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to download tags for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to download tags for') -argparser.add_argument( - 'placement_id', type=int, - help='The ID of the placement to download tags for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - placement_id = flags.placement_id - - try: - # Construct the request. - request = service.placements().generatetags( - profileId=profile_id, campaignId=campaign_id, - placementIds=[placement_id]) - - # Execute request and print response. - response = request.execute() - - for placement_tag in response['placementTags']: - print_placement_tag(placement_tag) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def print_placement_tag(placement_tag): - for tag_data in placement_tag['tagDatas']: - print ('%s - %s\n' - % (placement_tag['placementId'], tag_data['format'])) - - if 'impressionTag' in tag_data: - print '%s\n\n' % (tag_data['impressionTag']) - if 'clickTag' in tag_data: - print '%s\n\n' % (tag_data['clickTag']) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/find_and_download_file.py b/python/v3_4/find_and_download_file.py deleted file mode 100644 index 552e4d5..0000000 --- a/python/v3_4/find_and_download_file.py +++ /dev/null @@ -1,149 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""An end-to-end example of how to find and download a report file.""" - -import argparse -import io -import os -import sys - -import dfareporting_utils -from googleapiclient import http -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, help='The ID of the report to get a file for') - -# Chunk size to use when downloading report files. Defaults to 32MB. -CHUNK_SIZE = 32 * 1024 * 1024 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # 1. Find a file to download. - report_file = find_file(service, profile_id, report_id) - - if report_file: - # 2. (optional) Generate browser URL. - generate_browser_url(service, report_id, report_file['id']) - - # 3. Directly download the file. - direct_download_file(service, report_id, report_file['id']) - else: - print 'No file found for profile ID %d and report ID %d.' % (profile_id, - report_id) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def find_file(service, profile_id, report_id): - """Finds a report file to download.""" - target = None - - request = service.reports().files().list( - profileId=profile_id, reportId=report_id) - - while True: - response = request.execute() - - for report_file in response['items']: - if is_target_file(report_file): - target = report_file - break - - if not target and response['items'] and response['nextPageToken']: - request = service.reports().files().list_next(request, response) - else: - break - - if target: - print 'Found file %s with filename "%s".' % (target['id'], - target['fileName']) - return target - - print 'Unable to find file for profile ID %d and report ID %d.' % (profile_id, - report_id) - return None - - -def is_target_file(report_file): - # Provide custom validation logic here. - # For example purposes, any available file is considered valid. - return report_file['status'] == 'REPORT_AVAILABLE' - - -def generate_browser_url(service, report_id, file_id): - """Prints the browser download URL for the file.""" - report_file = service.files().get( - reportId=report_id, fileId=file_id).execute() - browser_url = report_file['urls']['browserUrl'] - - print 'File %s has browser URL: %s.' % (report_file['id'], browser_url) - - -def direct_download_file(service, report_id, file_id): - """Downloads a report file to disk.""" - # Retrieve the file metadata. - report_file = service.files().get( - reportId=report_id, fileId=file_id).execute() - - if report_file['status'] == 'REPORT_AVAILABLE': - # Prepare a local file to download the report contents to. - out_file = io.FileIO(generate_file_name(report_file), mode='wb') - - # Create a get request. - request = service.files().get_media(reportId=report_id, fileId=file_id) - - # Create a media downloader instance. - # Optional: adjust the chunk size used when downloading the file. - downloader = http.MediaIoBaseDownload( - out_file, request, chunksize=CHUNK_SIZE) - - # Execute the get request and download the file. - download_finished = False - while download_finished is False: - _, download_finished = downloader.next_chunk() - - print('File %s downloaded to %s' % (report_file['id'], - os.path.realpath(out_file.name))) - - -def generate_file_name(report_file): - """Generates a report file name based on the file metadata.""" - # If no filename is specified, use the file ID instead. - file_name = report_file['fileName'] or report_file['id'] - extension = '.csv' if report_file['format'] == 'CSV' else '.xml' - return file_name + extension - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/find_and_run_report.py b/python/v3_4/find_and_run_report.py deleted file mode 100644 index 208bfd6..0000000 --- a/python/v3_4/find_and_run_report.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""An end-to-end example of how to find and run a report.""" - -import argparse -import random -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to use') - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # 1. Find a report to run. - report = find_report(service, profile_id) - - if report: - # 2. Run the report. - report_file = run_report(service, profile_id, report['id']) - - # 3. Wait for the report file to be ready. - wait_for_report_file(service, report['id'], report_file['id']) - else: - print 'No report found for profile ID %d.\n' % profile_id - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def find_report(service, profile_id): - """Finds a report to run.""" - target = None - - # Construct the request. - request = service.reports().list(profileId=profile_id) - - while True: - response = request.execute() - - for report in response['items']: - if is_target_report(report): - target = report - break - - if not target and response['items'] and response['nextPageToken']: - request = service.reports().list_next(request, response) - else: - break - - if target: - print 'Found report %s with name "%s".' % (target['id'], target['name']) - return target - - print 'Unable to find report for profile ID %d.' % profile_id - return None - - -def is_target_report(report): - # Provide custom validation logic here. - # For example purposes, any report is considered valid. - return report is not None - - -def run_report(service, profile_id, report_id): - """Runs the report.""" - # Run the report. - report_file = service.reports().run( - profileId=profile_id, reportId=report_id).execute() - - print 'Running report %s, current file status is %s.' % ( - report_id, report_file['status']) - return report_file - - -def wait_for_report_file(service, report_id, file_id): - """Waits for the report file to finish processing.""" - # Wait for the report file to finish processing. - # An exponential backoff strategy is used to conserve request quota. - sleep = 0 - start_time = time.time() - while True: - report_file = service.files().get( - reportId=report_id, fileId=file_id).execute() - - status = report_file['status'] - if status == 'REPORT_AVAILABLE': - print 'File status is %s, ready to download.' % status - return - elif status != 'PROCESSING': - print 'File status is %s, processing failed.' % status - return - elif time.time() - start_time > MAX_RETRY_ELAPSED_TIME: - print 'File processing deadline exceeded.' - return - - sleep = next_sleep_interval(sleep) - print 'File status is %s, sleeping for %d seconds.' % (status, sleep) - time.sleep(sleep) - - -def next_sleep_interval(previous_sleep_interval): - """Calculates the next sleep interval based on the previous.""" - min_interval = previous_sleep_interval or MIN_RETRY_INTERVAL - max_interval = previous_sleep_interval * 3 or MIN_RETRY_INTERVAL - return min(MAX_RETRY_INTERVAL, random.randint(min_interval, max_interval)) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_ads.py b/python/v3_4/get_ads.py deleted file mode 100755 index a7d38ee..0000000 --- a/python/v3_4/get_ads.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all active ads your DFA user profile can see. - -Only name and ID are returned. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up ads for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.ads().list(profileId=profile_id, active=True) - - while True: - # Execute request and print response. - response = request.execute() - - for ad in response['ads']: - print 'Found ad with ID %s and name "%s".' % (ad['id'], ad['name']) - - if response['ads'] and response['nextPageToken']: - request = service.ads().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_advertiser_groups.py b/python/v3_4/get_advertiser_groups.py deleted file mode 100644 index c69c636..0000000 --- a/python/v3_4/get_advertiser_groups.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all advertiser groups for a specified user profile.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list activity groups for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.advertiserGroups().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for group in response['advertiserGroups']: - print ('Found advertiser group with ID %s and name "%s".' - % (group['id'], group['name'])) - - if response['advertiserGroups'] and response['nextPageToken']: - request = service.advertiserGroups().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_advertiser_landing_pages.py b/python/v3_4/get_advertiser_landing_pages.py deleted file mode 100644 index d183979..0000000 --- a/python/v3_4/get_advertiser_landing_pages.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all landing pages for the specified advertiser.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to look up advertiser landing pages for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to look up landing pages for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.advertiserLandingPages().list( - profileId=profile_id, advertiserIds=[advertiser_id]) - - while True: - # Execute request and print response. - response = request.execute() - - for landing_page in response['landingPages']: - print('Found advertiser landing page with ID %s and name "%s".' % - (landing_page['id'], landing_page['name'])) - - if response['landingPages'] and response['nextPageToken']: - request = service.advertiserLandingPages().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_advertisers.py b/python/v3_4/get_advertisers.py deleted file mode 100755 index dffc246..0000000 --- a/python/v3_4/get_advertisers.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all advertisers. - -Only advertiser name, ID and floodlight config ID will be returned. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up advertisers for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.advertisers().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for advertiser in response['advertisers']: - print ('Found advertiser with ID %s and name "%s".' - % (advertiser['id'], advertiser['name'])) - - if response['advertisers'] and response['nextPageToken']: - request = service.advertisers().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_campaigns.py b/python/v3_4/get_campaigns.py deleted file mode 100644 index 28b471a..0000000 --- a/python/v3_4/get_campaigns.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all existing campaigns for the specified user profile.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up campaigns for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.campaigns().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for campaign in response['campaigns']: - print ('Found campaign with ID %s and name "%s".' - % (campaign['id'], campaign['name'])) - - if response['campaigns'] and response['nextPageToken']: - request = service.campaigns().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_change_logs_for_advertiser.py b/python/v3_4/get_change_logs_for_advertiser.py deleted file mode 100644 index 6fa696a..0000000 --- a/python/v3_4/get_change_logs_for_advertiser.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays the change logs of a specified advertiser object. - -A similar pattern can be applied to get change logs for many other object -types. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up change logs for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to look up change logs for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.changeLogs().list( - profileId=profile_id, objectIds=[advertiser_id], - objectType='OBJECT_ADVERTISER') - - while True: - # Execute request and print response. - response = request.execute() - - for change_log in response['changeLogs']: - print( - '%s: Field "%s" from "%s" to "%s".' % - (change_log['action'], change_log['fieldName'], - change_log['oldValue'], change_log['newValue'])) - - if response['changeLogs'] and response['nextPageToken']: - request = service.changeLogs().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_compatible_fields.py b/python/v3_4/get_compatible_fields.py deleted file mode 100644 index 22fcf00..0000000 --- a/python/v3_4/get_compatible_fields.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get the compatible fields for a report.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to get compatible fields for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Retrieve the specified report resource - report = service.reports().get( - profileId=profile_id, reportId=report_id).execute() - - compatible_fields_type = get_compatible_fields_type(report['type']) - - # Construct the request - request = service.reports().compatibleFields().query( - profileId=profile_id, body=report) - - # Execute the request and print response. - response = request.execute() - - compatible_fields = response[compatible_fields_type] - print_fields('Dimensions', compatible_fields['dimensions']) - print_fields('Metrics', compatible_fields['metrics']) - print_fields('Dimension Filters', - compatible_fields['dimensionFilters']) - print_fields('Pivoted Activity Metrics', - compatible_fields['pivotedActivityMetrics']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def get_compatible_fields_type(report_type): - return { - 'CROSS_DIMENSION_REACH': 'crossDimensionReachReportCompatibleFields', - 'FLOODLIGHT': 'floodlightReportCompatibleFields', - 'PATH_TO_CONVERSION': 'pathToConversionReportCompatibleFields', - 'REACH': 'reachReportCompatibleFields' - }.get(report_type, 'reportCompatibleFields') - - -def print_fields(field_type, fields): - field_names = [field['name'] for field in fields] - print 'Compatible %s\n%s\n\n' % (field_type, ','.join(field_names)) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_content_categories.py b/python/v3_4/get_content_categories.py deleted file mode 100644 index 2300efd..0000000 --- a/python/v3_4/get_content_categories.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all available content categories.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up content categories for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.contentCategories().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for category in response['contentCategories']: - print ('Found content category with ID %s and name "%s".' - % (category['id'], category['name'])) - - if response['contentCategories'] and response['nextPageToken']: - request = service.contentCategories().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_creative_field_values.py b/python/v3_4/get_creative_field_values.py deleted file mode 100644 index c8cd19c..0000000 --- a/python/v3_4/get_creative_field_values.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all creative fields.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get creative field values for') -argparser.add_argument( - 'field_id', type=int, - help='The ID of the creative field to get values for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - field_id = flags.field_id - - try: - # Construct the request. - request = service.creativeFieldValues().list( - profileId=profile_id, creativeFieldId=field_id) - - while True: - # Execute request and print response. - response = request.execute() - - for value in response['creativeFieldValues']: - print ('Found creative field value with ID %s and value "%s".' - % (value['id'], value['value'])) - - if response['creativeFieldValues'] and response['nextPageToken']: - request = service.creativeFieldValues().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_creative_fields.py b/python/v3_4/get_creative_fields.py deleted file mode 100644 index 7493dfd..0000000 --- a/python/v3_4/get_creative_fields.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all creative fields.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get creative fields for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.creativeFields().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for field in response['creativeFields']: - print ('Found creative field with ID %s and name "%s".' - % (field['id'], field['name'])) - - if response['creativeFields'] and response['nextPageToken']: - request = service.creativeFields().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_creative_groups.py b/python/v3_4/get_creative_groups.py deleted file mode 100644 index 6a39896..0000000 --- a/python/v3_4/get_creative_groups.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all creative groups.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get creative groups for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.creativeGroups().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for group in response['creativeGroups']: - print ('Found creative group with ID %s and name "%s".' - % (group['id'], group['name'])) - - if response['creativeGroups'] and response['nextPageToken']: - request = service.advertisers().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_creatives.py b/python/v3_4/get_creatives.py deleted file mode 100644 index 0d97fed..0000000 --- a/python/v3_4/get_creatives.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all existing active creatives for a given advertiser. - -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up creatives for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to look up creatives for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.creatives().list( - profileId=profile_id, active=True, advertiserId=advertiser_id) - - while True: - # Execute request and print response. - response = request.execute() - - for creative in response['creatives']: - print ('Found %s creative with ID %s and name "%s".' - % (creative['type'], creative['id'], creative['name'])) - - if response['creatives'] and response['nextPageToken']: - request = service.creatives().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_dimension_values.py b/python/v3_4/get_dimension_values.py deleted file mode 100644 index f17f3ee..0000000 --- a/python/v3_4/get_dimension_values.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get all dimension values for a dimension.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get a report for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Create the dimension to query - dimension = { - 'dimensionName': 'advertiser', - 'startDate': '2012-01-01', - 'endDate': '2013-12-31' - } - - # Construct the request. - request = service.dimensionValues().query( - profileId=profile_id, body=dimension) - - while True: - # Execute request and print response. - response = request.execute() - - for value in response['items']: - print ('Found dimension value with ID %s and value "%s".' - % (value['id'], value['value'])) - - if response['items'] and response['nextPageToken']: - request = service.dimensionValues().query_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_files.py b/python/v3_4/get_files.py deleted file mode 100644 index c2c96ad..0000000 --- a/python/v3_4/get_files.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all the files for a profile.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct a get request for the specified profile. - request = service.files().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for report_file in response['items']: - print ('File with ID %s and file name "%s" has status "%s".' - % (report_file['id'], report_file['fileName'], - report_file['status'])) - - if response['items'] and response['nextPageToken']: - request = service.files().list_next(request, response) - else: - break - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_floodlight_activities.py b/python/v3_4/get_floodlight_activities.py deleted file mode 100644 index c7ffa6f..0000000 --- a/python/v3_4/get_floodlight_activities.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays floodlight activities for a given advertiser. - -To create an advertiser, run create_advertiser.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list activities for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to list activities for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.floodlightActivities().list( - profileId=profile_id, advertiserId=advertiser_id) - - while True: - # Execute request and print response. - response = request.execute() - - for activity in response['floodlightActivities']: - print ('Found floodlight activity with ID %s and name "%s".' - % (activity['id'], activity['name'])) - - if response['floodlightActivities'] and response['nextPageToken']: - request = service.floodlightActivities().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_floodlight_activity_groups.py b/python/v3_4/get_floodlight_activity_groups.py deleted file mode 100644 index ac17db7..0000000 --- a/python/v3_4/get_floodlight_activity_groups.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays floodlight activity groups for a given advertiser. - -To create an advertiser, run create_advertiser.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list activity groups for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to list activity groups for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.floodlightActivityGroups().list( - profileId=profile_id, advertiserId=advertiser_id) - - # Execute request and print response. - response = request.execute() - - for group in response['floodlightActivityGroups']: - print ('Found floodlight activity group with ID %s and name "%s".' - % (group['id'], group['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_placement_strategies.py b/python/v3_4/get_placement_strategies.py deleted file mode 100644 index 3999316..0000000 --- a/python/v3_4/get_placement_strategies.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all available placement strategies.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up placement strategies for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.placementStrategies().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for strategy in response['placementStrategies']: - print ('Found placement strategy with ID %s and name "%s".' - % (strategy['id'], strategy['name'])) - - if response['placementStrategies'] and response['nextPageToken']: - request = service.placementStrategies().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_placements.py b/python/v3_4/get_placements.py deleted file mode 100644 index 909d01e..0000000 --- a/python/v3_4/get_placements.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all available placements.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up placements for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.placements().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for placement in response['placements']: - print ('Found placement with ID %s and name "%s" for campaign "%s".' - % (placement['id'], placement['name'], - placement['campaignId'])) - - if response['placements'] and response['nextPageToken']: - request = service.placements().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_remarketing_lists.py b/python/v3_4/get_remarketing_lists.py deleted file mode 100644 index 59ee99b..0000000 --- a/python/v3_4/get_remarketing_lists.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Displays all remarketing lists owned by the specified advertiser. - -Note: the RemarketingLists resource will only return lists owned by the -specified advertiser. To see all lists that can be used for targeting ads -(including those shared from other accounts or advertisers), use the -TargetableRemarketingLists resource instead. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up remarketing lists for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to look up remarketing lists for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.remarketingLists().list( - profileId=profile_id, advertiserId=advertiser_id) - - while True: - # Execute request and print response. - response = request.execute() - - for remarketing_list in response['remarketingLists']: - print ('Found remarketing list with ID %s and name "%s."' - % (remarketing_list['id'], remarketing_list['name'])) - - if response['remarketingLists'] and response['nextPageToken']: - request = service.remarketingLists().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_report_files.py b/python/v3_4/get_report_files.py deleted file mode 100644 index f7b839d..0000000 --- a/python/v3_4/get_report_files.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all the files for a report.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to list files for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Construct a get request for the specified report. - request = service.reports().files().list( - profileId=profile_id, reportId=report_id) - - while True: - # Execute request and print response. - response = request.execute() - - for report_file in response['items']: - print ('Report file with ID %s and file name "%s" has status %s.' - % (report_file['id'], report_file['fileName'], - report_file['status'])) - - if response['items'] and response['nextPageToken']: - request = service.reports().files().list_next(request, response) - else: - break - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_reports.py b/python/v3_4/get_reports.py deleted file mode 100644 index 3c15b95..0000000 --- a/python/v3_4/get_reports.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all reports.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list reports for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.reports().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for report in response['items']: - print ('Found %s report with ID %s and name "%s".' - % (report['type'], report['id'], report['name'])) - - if response['items'] and response['nextPageToken']: - request = service.reports().list_next(request, response) - else: - break - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_sites.py b/python/v3_4/get_sites.py deleted file mode 100644 index b3720e5..0000000 --- a/python/v3_4/get_sites.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all existing sites.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sites for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.sites().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for site in response['sites']: - print ('Found site with ID %s and key name "%s".' - % (site['id'], site['keyName'])) - - if response['sites'] and response['nextPageToken']: - request = service.sites().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_size.py b/python/v3_4/get_size.py deleted file mode 100644 index a09f47a..0000000 --- a/python/v3_4/get_size.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all sizes for a given width and height.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sizes for') -argparser.add_argument( - 'height', type=int, - help='Width of the size to look up') -argparser.add_argument( - 'width', type=int, - help='Height of the size to look up') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - height = flags.height - width = flags.width - - try: - # Construct the request. - request = service.sizes().list( - profileId=profile_id, height=height, width=width) - - # Execute request and print response. - result = request.execute() - - for size in result['sizes']: - print 'Found size with ID %s.' % (size['id']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_subaccounts.py b/python/v3_4/get_subaccounts.py deleted file mode 100644 index d1f4c9b..0000000 --- a/python/v3_4/get_subaccounts.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all subaccounts. - -Note that the permissions assigned to a subaccount are not returned in a -human-readable format with this example. Run get_available_permissions.py to -see what permissions are available on a subaccount. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sites for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.subaccounts().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for subaccount in response['subaccounts']: - print ('Found subaccount with ID %s and name "%s".' - % (subaccount['id'], subaccount['name'])) - - if response['subaccounts'] and response['nextPageToken']: - request = service.subaccounts().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_targeting_templates.py b/python/v3_4/get_targeting_templates.py deleted file mode 100644 index a138fc8..0000000 --- a/python/v3_4/get_targeting_templates.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example retrieves all targeting templates for your DCM user profile. - -Displays name, ID, and advertiser ID for each targeting template found. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up targeting templates for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Limit the fields returned - fields = 'nextPageToken,targetingTemplates(advertiserId,id,name)' - - # Construct the request. - request = service.targetingTemplates().list(profileId=profile_id, - fields=fields) - - while True: - # Execute request and print response. - response = request.execute() - - for template in response['targetingTemplates']: - print ('Found targeting template with ID %s and name "%s" associated ' - 'with advertiser ID %s.' % (template['id'], template['name'], - template['advertiserId'])) - - if response['targetingTemplates'] and response['nextPageToken']: - request = service.targetingTemplates().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_user_role_permissions.py b/python/v3_4/get_user_role_permissions.py deleted file mode 100644 index 8ad2a02..0000000 --- a/python/v3_4/get_user_role_permissions.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all of the available subaccount permissions. - -To get a subaccount ID, run get_subaccounts.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list permissions for') -argparser.add_argument( - 'subaccount_id', type=int, - help='The ID of the subaccount to list permissions for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - subaccount_id = flags.subaccount_id - - try: - # Construct and execute the subaccount request. - request = service.subaccounts().get( - profileId=profile_id, id=subaccount_id) - - subaccount = request.execute() - - # Construct the user role permissions request. - request = service.userRolePermissions().list( - profileId=profile_id, ids=subaccount['availablePermissionIds']) - - # Execute request and print response. - result = request.execute() - - for permission in result['userRolePermissions']: - print ('Found user role permission with ID %s and name "%s".' - % (permission['id'], permission['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_user_roles.py b/python/v3_4/get_user_roles.py deleted file mode 100644 index cb78b36..0000000 --- a/python/v3_4/get_user_roles.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all user roles. - -The output is limited to include only ID, name, account ID and subaccount ID. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sites for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Limit the fields returned - fields = 'nextPageToken,userRoles(accountId,id,name,subaccountId)' - - # Construct the request. - request = service.userRoles().list(profileId=profile_id, fields=fields) - - while True: - # Execute request and print response. - response = request.execute() - - for user_role in response['userRoles']: - print ('Found user role with ID %s and name "%s".' - % (user_role['id'], user_role['name'])) - - if response['userRoles'] and response['nextPageToken']: - request = service.userRoles().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/get_userprofiles.py b/python/v3_4/get_userprofiles.py deleted file mode 100644 index d029d85..0000000 --- a/python/v3_4/get_userprofiles.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all user profiles.""" - -import sys - -import dfareporting_utils -from oauth2client import client - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - try: - # Construct the request. - request = service.userProfiles().list() - - # Execute request and print response. - response = request.execute() - - for profile in response['items']: - print ('Found user profile with ID %s and name "%s" for account %s.' - % (profile['profileId'], profile['userName'], - profile['accountId'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/insert_offline_mobile_conversion.py b/python/v3_4/insert_offline_mobile_conversion.py deleted file mode 100644 index d659e0d..0000000 --- a/python/v3_4/insert_offline_mobile_conversion.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Inserts an offline conversion attributed to a mobile device ID.""" - -import argparse -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'mobile_device_id', - help='The ID of the mobile device to attribute the conversion to') -argparser.add_argument( - 'floodlight_activity_id', type=int, - help='The ID of Floodlight activity this conversion is associated with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - floodlight_activity_id = flags.floodlight_activity_id - mobile_device_id = flags.mobile_device_id - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - current_time_in_micros = int(time.time() * 1000000) - - # Construct the conversion. - conversion = { - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': current_time_in_micros, - 'mobileDeviceId': mobile_device_id, - 'timestampMicros': current_time_in_micros - } - - # Insert the conversion. - request_body = {'conversions': [conversion]} - request = service.conversions().batchinsert(profileId=profile_id, - body=request_body) - response = request.execute() - - if not response['hasFailures']: - print ('Successfully inserted conversion for mobile device ID %s.' - % mobile_device_id) - else: - print ('Error(s) inserting conversion for mobile device ID %s.' - % mobile_device_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/insert_offline_user_conversion.py b/python/v3_4/insert_offline_user_conversion.py deleted file mode 100644 index 974c3f1..0000000 --- a/python/v3_4/insert_offline_user_conversion.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Inserts an offline conversion attributed to an encrypted user ID.""" - -import argparse -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'encrypted_user_id', - help='The encrypted user ID to attribute the conversion to') -argparser.add_argument( - 'encryption_source', - help='The source of the encrypted user ID') -argparser.add_argument( - 'encryption_entity_id', type=int, - help='The ID of the entity used to encrypt the supplied user ID') -argparser.add_argument( - 'encryption_entity_type', - help='The type of the entity used to encrypt the supplied user ID') -argparser.add_argument( - 'floodlight_activity_id', type=int, - help='The ID of Floodlight activity this conversion is associated with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - encrypted_user_id = flags.encrypted_user_id - encryption_entity_id = flags.encryption_entity_id - encryption_entity_type = flags.encryption_entity_type - encryption_source = flags.encryption_source - floodlight_activity_id = flags.floodlight_activity_id - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - current_time_in_micros = int(time.time() * 1000000) - - # Construct the conversion. - conversion = { - 'encryptedUserId': encrypted_user_id, - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': current_time_in_micros, - 'timestampMicros': current_time_in_micros - } - - # Construct the encryption info. - encryption_info = { - 'encryptionEntityId': encryption_entity_id, - 'encryptionEntityType': encryption_entity_type, - 'encryptionSource': encryption_source - } - - # Insert the conversion. - request_body = { - 'conversions': [conversion], - 'encryptionInfo': encryption_info - } - request = service.conversions().batchinsert(profileId=profile_id, - body=request_body) - response = request.execute() - - if not response['hasFailures']: - print ('Successfully inserted conversion for encrypted user ID %s.' - % encrypted_user_id) - else: - print ('Error(s) inserting conversion for encrypted user ID %s.' - % encrypted_user_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/run_report.py b/python/v3_4/run_report.py deleted file mode 100644 index cc83059..0000000 --- a/python/v3_4/run_report.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to run a report.""" - -import argparse -import random -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to run') - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Run the report. - report_file = service.reports().run(profileId=profile_id, - reportId=report_id).execute() - print 'File with ID %s has been created.' % report_file['id'] - - # Wait for the report file to finish processing. - # An exponential backoff strategy is used to conserve request quota. - sleep = 0 - start_time = time.time() - while True: - report_file = service.files().get(reportId=report_id, - fileId=report_file['id']).execute() - - status = report_file['status'] - if status == 'REPORT_AVAILABLE': - print 'File status is %s, ready to download.' % status - return - elif status != 'PROCESSING': - print 'File status is %s, processing failed.' % status - return - elif time.time() - start_time > MAX_RETRY_ELAPSED_TIME: - print 'File processing deadline exceeded.' - return - - sleep = next_sleep_interval(sleep) - print 'File status is %s, sleeping for %d seconds.' % (status, sleep) - time.sleep(sleep) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def next_sleep_interval(previous_sleep_interval): - """Calculates the next sleep interval based on the previous.""" - min_interval = previous_sleep_interval or MIN_RETRY_INTERVAL - max_interval = previous_sleep_interval * 3 or MIN_RETRY_INTERVAL - return min(MAX_RETRY_INTERVAL, random.randint(min_interval, max_interval)) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/share_remarketing_list_to_advertiser.py b/python/v3_4/share_remarketing_list_to_advertiser.py deleted file mode 100644 index 964bfc4..0000000 --- a/python/v3_4/share_remarketing_list_to_advertiser.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Shares an existing remarketing list with the specified advertiser.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to share remarketing lists as') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to share the remarketing list with') -argparser.add_argument( - 'remarketing_list_id', type=int, - help='The ID of the remarketing list to share') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = str(flags.advertiser_id) - list_id = flags.remarketing_list_id - - try: - # Load the existing share info. - share = service.remarketingListShares().get( - profileId=profile_id, remarketingListId=list_id).execute() - - share['sharedAdvertiserIds'] = share.get('sharedAdvertiserIds', []) - - if advertiser_id not in share['sharedAdvertiserIds']: - share['sharedAdvertiserIds'].append(advertiser_id) - - # Update the share info with the newly added advertiser ID. - response = service.remarketingListShares().update( - profileId=profile_id, body=share).execute() - - print ('Remarketing list %s is now shared to advertiser ID(s): %s.' - % (list_id, ','.join(response['sharedAdvertiserIds']))) - else: - print ('Remarketing list %s is already shared to advertiser %s' - % (list_id, advertiser_id)) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/target_ad_to_remarketing_list.py b/python/v3_4/target_ad_to_remarketing_list.py deleted file mode 100644 index 658e252..0000000 --- a/python/v3_4/target_ad_to_remarketing_list.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example targets an ad to a remarketing list. - -The first targetable remarketing list, either owned by or shared to the ad's -advertiser, will be used. To create a remarketing list, see -create_remarketing_list.py. To share a remarketing list with the ad's -advertiser, see share_remarketing_list_to_advertiser.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to use for targeting') -argparser.add_argument('ad_id', type=int, help='The ID of the ad to target') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - ad_id = flags.ad_id - - try: - # Retrieve the ad. - ad = service.ads().get(profileId=profile_id, id=ad_id).execute() - - # Retrieve a single targetable remarketing list for the ad. - lists = service.targetableRemarketingLists().list( - profileId=profile_id, advertiserId=ad['advertiserId'], - maxResults=1).execute() - - if lists['targetableRemarketingLists']: - remarketing_list = lists['targetableRemarketingLists'][0] - - # Update the ad with a list targeting expression - ad['remarketingListExpression'] = { - 'expression': remarketing_list['id'] - } - response = service.ads().update(profileId=profile_id, body=ad).execute() - - print('Ad %s updated to use remarketing list expression: "%s".' - % (response['id'], - response['remarketingListExpression']['expression'])) - else: - print 'No targetable remarketing lists found for ad with ID %d.' % ad_id - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/update_offline_mobile_conversion.py b/python/v3_4/update_offline_mobile_conversion.py deleted file mode 100644 index 9fd2736..0000000 --- a/python/v3_4/update_offline_mobile_conversion.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Updates an offline conversion attributed to a mobile device ID. - -To create a conversion attributed to a mobile device ID, run -insert_offline_mobile_conversion.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to update a conversion for') - -# Values that identify the existing conversion. -argparser.add_argument( - 'mobile_device_id', - help='The ID of the mobile device the conversion is attributed to.') -argparser.add_argument( - 'floodlight_activity_id', - type=int, - help='The ID of Floodlight activity the conversion is associated with') -argparser.add_argument('ordinal', help='The ordinal of the conversion.') -argparser.add_argument( - 'timestamp', type=int, help='The timestamp of the conversion.') - -# Values to update for the specified conversion. -argparser.add_argument( - 'new_quantity', - type=int, - help='The new quantity to set for the conversion.') -argparser.add_argument( - 'new_value', type=int, help='The new value to set for the conversion.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - floodlight_activity_id = flags.floodlight_activity_id - mobile_device_id = flags.mobile_device_id - ordinal = flags.ordinal - timestamp = flags.timestamp - new_quantity = flags.new_quantity - new_value = flags.new_value - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - # Construct the conversion object with values that identify the conversion - # to update. - conversion = { - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': ordinal, - 'mobileDeviceId': mobile_device_id, - 'timestampMicros': timestamp - } - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion['quantity'] = new_quantity - conversion['value'] = new_value - - # Update the conversion. - request_body = {'conversions': [conversion]} - request = service.conversions().batchupdate( - profileId=profile_id, body=request_body) - response = request.execute() - - if not response['hasFailures']: - print('Successfully updated conversion for mobile device ID %s.' % - mobile_device_id) - else: - print('Error(s) updating conversion for mobile device ID %s.' % - mobile_device_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_4/update_offline_user_conversion.py b/python/v3_4/update_offline_user_conversion.py deleted file mode 100644 index e7b9fff..0000000 --- a/python/v3_4/update_offline_user_conversion.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Updates an offline conversion attributed to an encrypted user ID. - -To create a conversion attributed to an encrypted user ID, run -insert_offline_user_conversion.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to update a conversion for') - -# Values that specify how the existing conversion is encrypted. -argparser.add_argument( - 'encrypted_user_id', - help='The encrypted user ID the conversion is attributed to') -argparser.add_argument( - 'encryption_source', help='The source of the encrypted user ID') -argparser.add_argument( - 'encryption_entity_id', - type=int, - help='The ID of the entity used to encrypt the supplied user ID') -argparser.add_argument( - 'encryption_entity_type', - help='The type of the entity used to encrypt the supplied user ID') - -# Values that identify the existing conversion. -argparser.add_argument( - 'floodlight_activity_id', - type=int, - help='The ID of Floodlight activity this conversion is associated with') -argparser.add_argument('ordinal', help='The ordinal of the conversion.') -argparser.add_argument( - 'timestamp', type=int, help='The timestamp of the conversion.') - -# Values to update for the specified conversion. -argparser.add_argument( - 'new_quantity', - type=int, - help='The new quantity to set for the conversion.') -argparser.add_argument( - 'new_value', type=int, help='The new value to set for the conversion.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - encrypted_user_id = flags.encrypted_user_id - encryption_entity_id = flags.encryption_entity_id - encryption_entity_type = flags.encryption_entity_type - encryption_source = flags.encryption_source - floodlight_activity_id = flags.floodlight_activity_id - ordinal = flags.ordinal - timestamp = flags.timestamp - new_quantity = flags.new_quantity - new_value = flags.new_value - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - # Construct the conversion object with values that identify the conversion - # to update. - conversion = { - 'encryptedUserId': encrypted_user_id, - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': ordinal, - 'timestampMicros': timestamp - } - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion['quantity'] = new_quantity - conversion['value'] = new_value - - # Construct the encryption info. - encryption_info = { - 'encryptionEntityId': encryption_entity_id, - 'encryptionEntityType': encryption_entity_type, - 'encryptionSource': encryption_source - } - - # Update the conversion. - request_body = { - 'conversions': [conversion], - 'encryptionInfo': encryption_info - } - request = service.conversions().batchupdate( - profileId=profile_id, body=request_body) - response = request.execute() - - if not response['hasFailures']: - print('Successfully updated conversion for encrypted user ID %s.' % - encrypted_user_id) - else: - print('Error(s) updating conversion for encrypted user ID %s.' % - encrypted_user_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/README.md b/python/v3_5/README.md deleted file mode 100644 index be20287..0000000 --- a/python/v3_5/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# DFA Reporting and Trafficking Python Samples - -This is a collection of samples written in Python which provide a starting place -for your experimentation into the DFA Reporting and Trafficking API. - -## Prerequisites - -Please make sure that you're running the latest version of Python 2 and have pip -installed. Use the following command from the samples directory to install all -dependencies: - -```Batchfile -$ pip install --upgrade google-api-python-client -``` - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Running the Examples - -I'm assuming you've checked out the code and are reading this from a local -directory. If not check out the code to a local directory. - -1. Start up a sample, e.g. - - $ python create_report.py - -2. Complete the authorization steps on your browser - -3. Examine your shell output, be inspired and start hacking an amazing new app! diff --git a/python/v3_5/__init__.py b/python/v3_5/__init__.py deleted file mode 100644 index f9fabef..0000000 --- a/python/v3_5/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Code samples for the DCM/DFA Reporting and Trafficking API.""" diff --git a/python/v3_5/assign_advertiser_to_advertiser_group.py b/python/v3_5/assign_advertiser_to_advertiser_group.py deleted file mode 100755 index c9a66fa..0000000 --- a/python/v3_5/assign_advertiser_to_advertiser_group.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example assigns an advertiser to an advertiser group. - -CAUTION: An advertiser that has campaigns associated with it cannot be -removed from an advertiser group once assigned. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add advertiser groups for') -argparser.add_argument( - 'advertiser_group_id', type=int, - help='The ID of the advertiser group to add to') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_group_id = flags.advertiser_group_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - advertiser = { - 'advertiserGroupId': advertiser_group_id - } - - request = service.advertisers().patch( - profileId=profile_id, id=advertiser_id, body=advertiser) - - # Execute request and print response. - response = request.execute() - - print ('Assigned advertiser with ID %s to advertiser group with ID %s.' - % (response['id'], response['advertiserGroupId'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/assign_creative_to_campaign.py b/python/v3_5/assign_creative_to_campaign.py deleted file mode 100755 index 940565e..0000000 --- a/python/v3_5/assign_creative_to_campaign.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example assigns a given creative to a given campaign. - -Note that both the creative and campaign must be associated with the same -advertiser. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to create this association as') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to associate the creative with') -argparser.add_argument( - 'creative_id', type=int, - help='The ID of the creative to be associated') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - creative_id = flags.creative_id - - try: - # Construct the request. - association = { - 'creativeId': creative_id - } - - request = service.campaignCreativeAssociations().insert( - profileId=profile_id, campaignId=campaign_id, body=association) - - # Execute request and print response. - response = request.execute() - - print ('Creative with ID %s is now associated with campaign %s.' - % (response['creativeId'], campaign_id)) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/authenticate_using_service_account.py b/python/v3_5/authenticate_using_service_account.py deleted file mode 100644 index ce818f5..0000000 --- a/python/v3_5/authenticate_using_service_account.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example demonstrates how to authenticate using a service account. - -An optional Google account email to impersonate may be specified as follows: - authenticate_using_service_account.py -i - -This optional flag only applies to service accounts which have domain-wide -delegation enabled and wish to make API requests on behalf of an account -within that domain. Using this flag will not allow you to impersonate a -user from a domain you don't own (e.g., gmail.com). -""" - -import argparse -import sys - -from googleapiclient import discovery -import httplib2 -from oauth2client import client -from oauth2client import tools -from oauth2client.service_account import ServiceAccountCredentials - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'path_to_service_account_json_file', - help='Path to the service account JSON file to use for authenticating.') -argparser.add_argument( - '-i', - '--impersonation_email', - help='Google account email to impersonate.') - -# The OAuth 2.0 scopes to request. -OAUTH_SCOPES = ['https://www.googleapis.com/auth/dfareporting'] - - -def main(argv): - # Retrieve command line arguments. - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter, - parents=[tools.argparser, argparser]) - flags = parser.parse_args(argv[1:]) - - # Authenticate using the supplied service account credentials - http = authenticate_using_service_account( - flags.path_to_service_account_json_file, - flags.impersonation_email) - - # Construct a service object via the discovery service. - service = discovery.build('dfareporting', 'v3.5', http=http) - - try: - # Construct the request. - request = service.userProfiles().list() - - # Execute request and print response. - response = request.execute() - - for profile in response['items']: - print('Found user profile with ID %s and user name "%s".' % - (profile['profileId'], profile['userName'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def authenticate_using_service_account(path_to_service_account_json_file, - impersonation_email): - """Authorizes an httplib2.Http instance using service account credentials.""" - # Load the service account credentials from the specified JSON keyfile. - credentials = ServiceAccountCredentials.from_json_keyfile_name( - path_to_service_account_json_file, - scopes=OAUTH_SCOPES) - - # Configure impersonation (if applicable). - if impersonation_email: - credentials = credentials.create_delegated(impersonation_email) - - # Use the credentials to authorize an httplib2.Http instance. - http = credentials.authorize(httplib2.Http()) - - return http - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/authenticate_using_user_account.py b/python/v3_5/authenticate_using_user_account.py deleted file mode 100644 index f4d3eea..0000000 --- a/python/v3_5/authenticate_using_user_account.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example demonstrates how to authenticate using a user account. - -Utilizes the OAuth 2.0 installed application flow. -""" - -import argparse -import sys - -from googleapiclient import discovery -import httplib2 -from oauth2client import client -from oauth2client import tools -from oauth2client.file import Storage - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'path_to_client_secrets_file', - help='Path to the client_secrets.json file to use for authenticating.') - -# Filename used for the credential store. -CREDENTIAL_STORE_FILE = 'auth-sample.dat' - -# The OAuth 2.0 scopes to request. -OAUTH_SCOPES = ['https://www.googleapis.com/auth/dfareporting'] - - -def main(argv): - # Retrieve command line arguments. - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter, - parents=[tools.argparser, argparser]) - flags = parser.parse_args(argv[1:]) - - # Authenticate using the supplied user account credentials - http = authenticate_using_user_account(flags.path_to_client_secrets_file) - - # Construct a service object via the discovery service. - service = discovery.build('dfareporting', 'v3.5', http=http) - - try: - # Construct the request. - request = service.userProfiles().list() - - # Execute request and print response. - response = request.execute() - - for profile in response['items']: - print('Found user profile with ID %s and user name "%s".' % - (profile['profileId'], profile['userName'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def authenticate_using_user_account(path_to_client_secrets_file): - """Authorizes an httplib2.Http instance using user account credentials.""" - # Set up a Flow object to be used if we need to authenticate. - flow = client.flow_from_clientsecrets( - path_to_client_secrets_file, scope=OAUTH_SCOPES) - - # Check whether credentials exist in the credential store. Using a credential - # store allows auth credentials to be cached, so they survive multiple runs - # of the application. This avoids prompting the user for authorization every - # time the access token expires, by remembering the refresh token. - storage = Storage(CREDENTIAL_STORE_FILE) - credentials = storage.get() - - # If no credentials were found, go through the authorization process and - # persist credentials to the credential store. - if credentials is None or credentials.invalid: - credentials = tools.run_flow(flow, storage, - tools.argparser.parse_known_args()[0]) - - # Use the credentials to authorize an httplib2.Http instance. - http = credentials.authorize(httplib2.Http()) - - return http - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/client_secrets.json b/python/v3_5/client_secrets.json deleted file mode 100644 index f9cf7ff..0000000 --- a/python/v3_5/client_secrets.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "installed": { - "client_id": "[[INSERT CLIENT ID HERE]]", - "client_secret": "[[INSERT CLIENT SECRET HERE]]", - "redirect_uris": [], - "auth_uri": "https://accounts.google.com/o/oauth2/auth", - "token_uri": "https://accounts.google.com/o/oauth2/token" - } -} \ No newline at end of file diff --git a/python/v3_5/configure_dynamic_asset_selection.py b/python/v3_5/configure_dynamic_asset_selection.py deleted file mode 100644 index 5c3ec29..0000000 --- a/python/v3_5/configure_dynamic_asset_selection.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example enables dynamic asset selection for an in-stream video creative. - -Requires an existing in-stream video creative, a new video asset, and a -targeting template ID as input. To get an in-stream video creative, run -create_instream_video_creative.py. To get a targeting template, run -create_targeting_template.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to configure dynamic asset selection for') -argparser.add_argument( - 'creative_id', type=int, - help='The ID of the in-stream video creative to configure selection for.') -argparser.add_argument( - 'template_id', type=int, - help='The ID of the template to use for targeting.') -argparser.add_argument( - 'video_name', help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_video_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - creative_id = flags.creative_id - template_id = flags.template_id - path_to_video_file = flags.path_to_video_file - video_name = flags.video_name - - try: - # Retrieve the specified creative. - creative = service.creatives().get(profileId=profile_id, - id=creative_id).execute() - - if not creative or creative['type'] != 'INSTREAM_VIDEO': - sys.exit('Invalid creative specified.') - - if 'creativeAssetSelection' not in creative: - # Locate an existing video asset to use as a default. - default_asset_id = next((asset['id'] - for asset in creative['creativeAssets'] - if asset['role'] == 'PARENT_VIDEO'), None) - - if not default_asset_id: - sys.exit('Default video asset could not be found.') - - # Enable dynamic asset selection for the creative. - creative['dynamicAssetSelection'] = True - - # Create a new selection using the existing asset as a default. - creative['creativeAssetSelection'] = { - 'defaultAssetId': default_asset_id, - 'rules': [] - } - - # Upload the new video asset and add it to the creative. - video_asset = upload_creative_asset( - service, profile_id, creative['advertiserId'], video_name, - path_to_video_file, 'VIDEO') - - creative['creativeAssets'].append({ - 'assetIdentifier': video_asset['assetIdentifier'], - 'role': 'PARENT_VIDEO' - }) - - # Create a rule targeting the new video asset and add it to the creative. - creative['creativeAssetSelection']['rules'].append({ - 'assetId': video_asset['id'], - 'name': 'Test rule for asset %s' % video_asset['id'], - 'targetingTemplateId': template_id - }) - - request = service.creatives().update(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Dynamic asset selection enabled for creative with ID %s.' - % response['id']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns a creative asset metadata object.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_advertiser.py b/python/v3_5/create_advertiser.py deleted file mode 100755 index f396e99..0000000 --- a/python/v3_5/create_advertiser.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an advertiser in a given DFA account.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add an advertiser for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save advertiser. - advertiser = { - 'name': 'Test Advertiser', - 'status': 'APPROVED' - } - - request = service.advertisers().insert( - profileId=profile_id, body=advertiser) - - # Execute request and print response. - response = request.execute() - - print ('Created advertiser with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_advertiser_group.py b/python/v3_5/create_advertiser_group.py deleted file mode 100755 index 02a1edd..0000000 --- a/python/v3_5/create_advertiser_group.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an advertiser group.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add an advertiser group for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save advertiser. - advertiser_group = { - 'name': 'Test Advertiser Group' - } - - request = service.advertiserGroups().insert( - profileId=profile_id, body=advertiser_group) - - # Execute request and print response. - response = request.execute() - - print ('Created advertiser group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_advertiser_landing_page.py b/python/v3_5/create_advertiser_landing_page.py deleted file mode 100755 index aab6db9..0000000 --- a/python/v3_5/create_advertiser_landing_page.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an advertiser landing page.""" - -import argparse -import sys -import uuid - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to add an advertiser landing page for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to associate the landing page with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct a landing page object. - landing_page = { - 'name': 'Test Landing Page #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'archived': 'false', - 'url': 'https://www.google.com' - } - - request = service.advertiserLandingPages().insert( - profileId=profile_id, body=landing_page) - - # Execute request and print response. - response = request.execute() - - print('Created advertiser landing page with ID %s and name "%s".' % - (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_campaign.py b/python/v3_5/create_campaign.py deleted file mode 100755 index a946587..0000000 --- a/python/v3_5/create_campaign.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a campaign in a given advertiser. - -To create an advertiser, run create_advertiser.py. -""" - -import argparse -import sys -import uuid - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a campaign for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to associate the campaign with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Construct and save campaign. - campaign = { - 'name': 'Test Campaign #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'archived': 'false', - 'defaultLandingPageId': default_landing_page['id'], - 'startDate': '2015-01-01', - 'endDate': '2020-01-01' - } - - request = service.campaigns().insert(profileId=profile_id, body=campaign) - - # Execute request and print response. - response = request.execute() - - print('Created campaign with ID %s and name "%s".' % (response['id'], - response['name'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def get_advertiser_landing_page(service, profile_id, advertiser_id): - # Retrieve a single landing page from the specified advertiser. - response = service.advertiserLandingPages().list( - profileId=profile_id, advertiserIds=[advertiser_id], - maxResults=1).execute() - - if not response['landingPages']: - sys.exit( - 'No landing pages found for advertiser with ID %d.' % advertiser_id) - - return response['landingPages'][0] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_campaign_event_tag.py b/python/v3_5/create_campaign_event_tag.py deleted file mode 100755 index 4d061de..0000000 --- a/python/v3_5/create_campaign_event_tag.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an event tag for the specified campaign.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add an event tag for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to add an event tag for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - - try: - # Construct and save event tag. - event_tag = { - 'campaignId': campaign_id, - 'name': 'Test Campaign Event Tag', - 'status': 'ENABLED', - 'type': 'CLICK_THROUGH_EVENT_TAG', - 'url': 'https://www.google.com' - } - - request = service.eventTags().insert(profileId=profile_id, body=event_tag) - - # Execute request and print response. - response = request.execute() - - print ('Created campaign event tag with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_content_category.py b/python/v3_5/create_content_category.py deleted file mode 100755 index c13ccfd..0000000 --- a/python/v3_5/create_content_category.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a content category with given name and description.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a content category for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save content category. - content_category = { - 'name': 'Test Category' - } - - request = service.contentCategories().insert( - profileId=profile_id, body=content_category) - - # Execute request and print response. - response = request.execute() - - print ('Created content category with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_creative_field.py b/python/v3_5/create_creative_field.py deleted file mode 100644 index 1f3655e..0000000 --- a/python/v3_5/create_creative_field.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a creative field associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a creative field for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a creative field for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct and save creative field - creative_field = { - 'advertiserId': advertiser_id, - 'name': 'Test Creative Field' - } - - request = service.creativeFields().insert( - profileId=profile_id, body=creative_field) - - # Execute request and print response. - response = request.execute() - - print ('Created creative field with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_creative_field_value.py b/python/v3_5/create_creative_field_value.py deleted file mode 100644 index 21413a4..0000000 --- a/python/v3_5/create_creative_field_value.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a creative field value for a given creative field. - -To get the creative field ID, run get_creative_fields.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a creative field value for') -argparser.add_argument( - 'field_id', type=int, - help='The ID of the creative field to add a value for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - field_id = flags.field_id - - try: - # Construct and save creative field value - field_value = { - 'value': 'Test Creative Field Value' - } - - request = service.creativeFieldValues().insert( - profileId=profile_id, creativeFieldId=field_id, body=field_value) - - # Execute request and print response. - response = request.execute() - - print ('Created creative field value with ID %s and value "%s".' - % (response['id'], response['value'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_creative_group.py b/python/v3_5/create_creative_group.py deleted file mode 100644 index c852e1e..0000000 --- a/python/v3_5/create_creative_group.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a creative group associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. Valid group numbers are -limited to 1 or 2. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a creative group for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a creative group for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct and save creative group - creative_group = { - 'advertiserId': advertiser_id, - 'groupNumber': 1, - 'name': 'Test Creative Group' - } - - request = service.creativeGroups().insert( - profileId=profile_id, body=creative_group) - - # Execute request and print response. - response = request.execute() - - print ('Created creative group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_display_image_gallery_creative.py b/python/v3_5/create_display_image_gallery_creative.py deleted file mode 100755 index 624a9ab..0000000 --- a/python/v3_5/create_display_image_gallery_creative.py +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a display image gallery creative. - -Requires two image assets and an advertiser ID as input. To get an advertiser -ID, run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'size_id', type=int, - help='The ID of the size of this creative.') -argparser.add_argument( - 'image1_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_image1_file', - help='Path to the asset file to be uploaded.') -argparser.add_argument( - 'image2_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_image2_file', - help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - image1_name = flags.image1_name - image2_name = flags.image2_name - path_to_image1_file = flags.path_to_image1_file - path_to_image2_file = flags.path_to_image2_file - size_id = flags.size_id - - try: - # Upload the first image asset - image1_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, image1_name, path_to_image1_file, - 'HTML_IMAGE') - - # Upload the second image asset - image2_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, image2_name, path_to_image2_file, - 'HTML_IMAGE') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'autoAdvanceImages': True, - 'clickTags': [ - {'eventName': image1_asset_id['name'], - 'name': image1_asset_id['name']}, - {'eventName': image2_asset_id['name'], - 'name': image2_asset_id['name']} - ], - 'creativeAssets': [ - {'assetIdentifier': image1_asset_id, 'role': 'PRIMARY'}, - {'assetIdentifier': image2_asset_id, 'role': 'PRIMARY'}, - ], - 'name': 'Test display image gallery creative', - 'size': {'id': size_id}, - 'type': 'DISPLAY_IMAGE_GALLERY' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created display image gallery creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_display_redirect_creative.py b/python/v3_5/create_display_redirect_creative.py deleted file mode 100755 index 3f2c7b8..0000000 --- a/python/v3_5/create_display_redirect_creative.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a display redirect creative. - -To get a size ID, run get_size.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'image_url', - help='URL of the image to associate with this creative.') -argparser.add_argument( - 'size_id', type=int, - help='The ID of the size of the specified image.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - image_url = flags.image_url - size_id = flags.size_id - - try: - # Construct the basic creative structure. - creative = { - 'advertiserId': advertiser_id, - 'name': 'Test display redirect creative', - 'redirect_url': image_url, - 'size': {'id': size_id}, - 'type': 'DISPLAY_REDIRECT' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created display redirect creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_floodlight_activity.py b/python/v3_5/create_floodlight_activity.py deleted file mode 100755 index db11f5e..0000000 --- a/python/v3_5/create_floodlight_activity.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a floodlight activity in a given activity group. - -To create an activity group, run create_floodlight_activity_group.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'activity_group_id', type=int, - help='The ID of the floodlight activity group to create an activity for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - activity_group_id = flags.activity_group_id - - try: - # Construct and save floodlight activity. - floodlight_activity = { - 'countingMethod': 'STANDARD_COUNTING', - 'expectedUrl': 'http://www.google.com', - 'floodlightActivityGroupId': activity_group_id, - 'floodlightTagType': 'GLOBAL_SITE_TAG', - 'name': 'Test Floodlight Activity' - } - - request = service.floodlightActivities().insert( - profileId=profile_id, body=floodlight_activity) - - # Execute request and print response. - response = request.execute() - - print ('Created floodlight activity with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_floodlight_activity_group.py b/python/v3_5/create_floodlight_activity_group.py deleted file mode 100755 index 7075be8..0000000 --- a/python/v3_5/create_floodlight_activity_group.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a new activity group for a floodlight configuration. - -To get a floodlight configuration ID, run get_advertisers.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'floodlight_config_id', type=int, - help='The ID of the floodlight config to create a group for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - floodlight_config_id = flags.floodlight_config_id - - try: - # Construct and save floodlight activity group. - activity_group = { - 'name': 'Test Floodlight Activity Group', - 'floodlightConfigurationId': floodlight_config_id, - 'type': 'COUNTER' - } - - request = service.floodlightActivityGroups().insert( - profileId=profile_id, body=activity_group) - - # Execute request and print response. - response = request.execute() - - print ('Created floodlight activity group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_html5_display_creative.py b/python/v3_5/create_html5_display_creative.py deleted file mode 100755 index f3ab214..0000000 --- a/python/v3_5/create_html5_display_creative.py +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an HTML5 display creative. - -Requires an HTML5 asset, backup image asset, and an advertiser ID as input. -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'size_id', type=int, help='The ID of the size of this creative.') -argparser.add_argument( - 'html5_asset_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_html5_asset_file', help='Path to the asset file to be uploaded.') -argparser.add_argument( - 'backup_image_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_backup_image_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - backup_image_name = flags.backup_image_name - html5_asset_name = flags.html5_asset_name - path_to_backup_image_file = flags.path_to_backup_image_file - path_to_html5_asset_file = flags.path_to_html5_asset_file - size_id = flags.size_id - - try: - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Upload the HTML5 asset - html5_asset_id = upload_creative_asset(service, profile_id, advertiser_id, - html5_asset_name, - path_to_html5_asset_file, 'HTML') - - # Upload the backup image asset - backup_image_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, backup_image_name, - path_to_backup_image_file, 'HTML_IMAGE') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'backupImageClickThroughUrl': { - 'landingPageId': default_landing_page['id'] - }, - 'backupImageReportingLabel': 'backup_image_exit', - 'backupImageTargetWindow': {'targetWindowOption': 'NEW_WINDOW'}, - 'clickTags': [{ - 'eventName': 'exit', - 'name': 'click_tag', - 'clickThroughUrl': {'landingPageId': default_landing_page['id']} - }], - 'creativeAssets': [ - {'assetIdentifier': html5_asset_id, 'role': 'PRIMARY'}, - {'assetIdentifier': backup_image_asset_id, 'role': 'BACKUP_IMAGE'} - ], - 'name': 'Test HTML5 display creative', - 'size': {'id': size_id}, - 'type': 'DISPLAY' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print('Created HTML5 display creative with ID %s and name "%s".' % - (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def get_advertiser_landing_page(service, profile_id, advertiser_id): - # Retrieve a single landing page from the specified advertiser. - response = service.advertiserLandingPages().list( - profileId=profile_id, advertiserIds=[advertiser_id], - maxResults=1).execute() - - if not response['landingPages']: - sys.exit( - 'No landing pages found for advertiser with ID %d.' % advertiser_id) - - return response['landingPages'][0] - - -def upload_creative_asset(service, profile_id, advertiser_id, asset_name, - path_to_asset_file, asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = {'assetIdentifier': {'name': asset_name, 'type': asset_type}} - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_image_display_creative.py b/python/v3_5/create_image_display_creative.py deleted file mode 100755 index dd5ec44..0000000 --- a/python/v3_5/create_image_display_creative.py +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an image display creative. - -Requires an image asset and advertiser ID as input. To get an advertiser ID, -run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'size_id', type=int, - help='The ID of the size of this creative.') -argparser.add_argument( - 'image_name', - help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_image_file', - help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - image_name = flags.image_name - path_to_image_file = flags.path_to_image_file - size_id = flags.size_id - - try: - # Upload the creative asset - creative_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, image_name, path_to_image_file, - 'HTML_IMAGE') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'creativeAssets': [ - {'assetIdentifier': creative_asset_id, 'role': 'PRIMARY'} - ], - 'name': 'Test image display creative', - 'size': {'id': size_id}, - 'type': 'DISPLAY' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created image display creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_instream_audio_creative.py b/python/v3_5/create_instream_audio_creative.py deleted file mode 100755 index 5c996c1..0000000 --- a/python/v3_5/create_instream_audio_creative.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an in-stream audio creative. - -Requires an audio asset and advertiser ID as input. To get an advertiser ID, -run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'audio_name', help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_audio_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - path_to_audio_file = flags.path_to_audio_file - audio_name = flags.audio_name - - try: - # Upload the creative asset - creative_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, audio_name, path_to_audio_file, - 'AUDIO') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'creativeAssets': [ - {'assetIdentifier': creative_asset_id, 'role': 'PARENT_AUDIO'} - ], - 'name': 'Test in-stream audio creative', - 'type': 'INSTREAM_AUDIO' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created in-stream audio creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_instream_video_creative.py b/python/v3_5/create_instream_video_creative.py deleted file mode 100755 index 4cc64af..0000000 --- a/python/v3_5/create_instream_video_creative.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an in-stream video creative. - -Requires a video asset and advertiser ID as input. To get an advertiser ID, -run get_advertisers.py. -""" - -import argparse -import sys - -from apiclient.http import MediaFileUpload -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') -argparser.add_argument( - 'video_name', help='Suggested name to use for the uploaded creative asset.') -argparser.add_argument( - 'path_to_video_file', help='Path to the asset file to be uploaded.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - path_to_video_file = flags.path_to_video_file - video_name = flags.video_name - - try: - # Upload the creative asset - creative_asset_id = upload_creative_asset( - service, profile_id, advertiser_id, video_name, path_to_video_file, - 'VIDEO') - - # Construct the creative structure. - creative = { - 'advertiserId': advertiser_id, - 'creativeAssets': [ - {'assetIdentifier': creative_asset_id, 'role': 'PARENT_VIDEO'} - ], - 'name': 'Test in-stream video creative', - 'type': 'INSTREAM_VIDEO' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created in-stream video creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def upload_creative_asset( - service, profile_id, advertiser_id, asset_name, path_to_asset_file, - asset_type): - """Uploads a creative asset and returns an assetIdentifier.""" - # Construct the creative asset metadata - creative_asset = { - 'assetIdentifier': { - 'name': asset_name, - 'type': asset_type - } - } - - media = MediaFileUpload(path_to_asset_file) - if not media.mimetype(): - media = MediaFileUpload(path_to_asset_file, 'application/octet-stream') - - response = service.creativeAssets().insert( - advertiserId=advertiser_id, - profileId=profile_id, - media_body=media, - body=creative_asset).execute() - - return response['assetIdentifier'] - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_placement.py b/python/v3_5/create_placement.py deleted file mode 100755 index 762ed6e..0000000 --- a/python/v3_5/create_placement.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates an agency paid regular placement in a given campaign. - -Requires the DFA site ID and campaign ID in which the placement will be created -into. To create a campaign, run create_campaign.py. To get DFA site ID, run -get_site.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to associate the placement with') -argparser.add_argument( - 'site_id', type=int, - help='The ID of the site to associate the placement with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - site_id = flags.site_id - - try: - # Look up the campaign - campaign = service.campaigns().get( - profileId=profile_id, id=campaign_id).execute() - - # Construct and save placement. - placement = { - 'name': 'Test Placement', - 'campaignId': campaign_id, - 'compatibility': 'DISPLAY', - 'siteId': site_id, - 'size': { - 'height': '1', - 'width': '1' - }, - 'paymentSource': 'PLACEMENT_AGENCY_PAID', - 'tagFormats': ['PLACEMENT_TAG_STANDARD'] - } - - # Set the pricing schedule for the placement. - placement['pricingSchedule'] = { - 'startDate': campaign['startDate'], - 'endDate': campaign['endDate'], - 'pricingType': 'PRICING_TYPE_CPM' - } - - request = service.placements().insert(profileId=profile_id, body=placement) - - # Execute request and print response. - response = request.execute() - - print ('Created placement with ID %s and name "%s".' - % (long(response['id']), response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_placement_group.py b/python/v3_5/create_placement_group.py deleted file mode 100755 index 4103571..0000000 --- a/python/v3_5/create_placement_group.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a placement group in a given campaign. - -Requires the DFA site ID and campaign ID in which the placement group will be -created into. To create a campaign, run create_campaign.py. To get DFA site ID, -run get_site.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement group for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to associate the placement group with') -argparser.add_argument( - 'site_id', type=int, - help='The ID of the site to associate the placement group with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - site_id = flags.site_id - - try: - # Look up the campaign - campaign = service.campaigns().get( - profileId=profile_id, id=campaign_id).execute() - - # Construct and save placement. - placement_group = { - 'name': 'Test Placement Group', - 'campaignId': campaign_id, - 'siteId': site_id, - 'placementGroupType': 'PLACEMENT_PACKAGE', - 'pricingSchedule': { - 'startDate': campaign['startDate'], - 'endDate': campaign['endDate'], - 'pricingType': 'PRICING_TYPE_CPM' - } - } - - request = service.placementGroups().insert( - profileId=profile_id, body=placement_group) - - # Execute request and print response. - response = request.execute() - - print ('Created placement group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_placement_strategy.py b/python/v3_5/create_placement_strategy.py deleted file mode 100755 index d5c8bf5..0000000 --- a/python/v3_5/create_placement_strategy.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a placement strategy with the given name.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement strategy for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct and save placement strategy. - placement_strategy = { - 'name': 'Test Strategy' - } - - request = service.placementStrategies().insert( - profileId=profile_id, body=placement_strategy) - - # Execute request and print response. - response = request.execute() - - print ('Created placement strategy with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_remarketing_list.py b/python/v3_5/create_remarketing_list.py deleted file mode 100644 index 644b401..0000000 --- a/python/v3_5/create_remarketing_list.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Creates a remarketing list for a given advertiser and floodlight activity. - -Note: this sample assumes that the floodlight activity specified has a U1 custom -floodlight variable. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a remarketing list for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a remarketing list for') -argparser.add_argument( - 'activity_id', type=int, - help='The ID of the floodlight activity to add a remarketing list for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - activity_id = flags.activity_id - - try: - # Create a list population term. - # This term matches all visitors with a U1 value exactly matching - # "test_value" - term = { - 'operator': 'STRING_EQUALS', - 'type': 'CUSTOM_VARIABLE_TERM', - 'value': 'test_value', - 'variableName': 'U1' - } - - # Add the term to a clause and the clause to a population rule. - # This rule will target all visitors who trigger the specified floodlight - # activity and satisfy the custom rule defined in the list population term. - rule = { - 'floodlightActivityId': activity_id, - 'listPopulationClauses': {'terms': [term]} - } - - # Create the remarketing list. - remarketing_list = { - 'name': 'Test Remarketing List', - 'active': 'true', - 'advertiserId': advertiser_id, - 'lifeSpan': 30, - 'listPopulationRule': rule - } - - request = service.remarketingLists().insert( - profileId=profile_id, body=remarketing_list) - - # Execute request and print response. - response = request.execute() - - print ('Created remarketing list with ID %s and name "%s."' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_report.py b/python/v3_5/create_report.py deleted file mode 100644 index e51aaa1..0000000 --- a/python/v3_5/create_report.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the 'License'); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""An end-to-end example of how to create and configure a standard report.""" - -import argparse -from datetime import date -from datetime import timedelta -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to create a report for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # 1. Create a report resource. - report = create_report_resource() - - # 2. Define the report criteria. - define_report_criteria(report) - - # 3. (optional) Look up compatible fields. - find_compatible_fields(service, profile_id, report) - - # 4. Add dimension filters to the report criteria. - add_dimension_filters(service, profile_id, report) - - # 5. Save the report resource. - report = insert_report_resource(service, profile_id, report) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def create_report_resource(): - """Creates a report resource.""" - report = { - # Set the required fields "name" and "type". - 'name': 'Example Standard Report', - 'type': 'STANDARD', - # Set optional fields. - 'fileName': 'example_report', - 'format': 'CSV' - } - - print 'Creating %s report resource with name "%s".' % (report['type'], - report['name']) - - return report - - -def define_report_criteria(report): - """Defines a criteria for the report.""" - # Define a date range to report on. This example uses explicit start and end - # dates to mimic the "LAST_30_DAYS" relative date range. - end_date = date.today() - start_date = end_date - timedelta(days=30) - - # Create a report criteria. - criteria = { - 'dateRange': { - 'startDate': start_date.strftime('%Y-%m-%d'), - 'endDate': end_date.strftime('%Y-%m-%d') - }, - 'dimensions': [{ - 'name': 'advertiser' - }], - 'metricNames': ['clicks', 'impressions'] - } - - # Add the criteria to the report resource. - report['criteria'] = criteria - - print '\nAdded report criteria:\n%s' % criteria - - -def find_compatible_fields(service, profile_id, report): - """Finds and adds a compatible dimension/metric to the report.""" - fields = service.reports().compatibleFields().query( - profileId=profile_id, body=report).execute() - - report_fields = fields['reportCompatibleFields'] - - if report_fields['dimensions']: - # Add a compatible dimension to the report. - report['criteria']['dimensions'].append({ - 'name': report_fields['dimensions'][0]['name'] - }) - elif report_fields['metrics']: - # Add a compatible metric to the report. - report['criteria']['metricNames'].append( - report_fields['metrics'][0]['name']) - - print('\nUpdated report criteria (with compatible fields):\n%s' % - report['criteria']) - - -def add_dimension_filters(service, profile_id, report): - """Finds and adds a valid dimension filter to the report.""" - # Query advertiser dimension values for report run dates. - request = { - 'dimensionName': 'advertiser', - 'endDate': report['criteria']['dateRange']['endDate'], - 'startDate': report['criteria']['dateRange']['startDate'] - } - - values = service.dimensionValues().query( - profileId=profile_id, body=request).execute() - - if values['items']: - # Add a value as a filter to the report criteria. - report['criteria']['dimensionFilters'] = [values['items'][0]] - - print('\nUpdated report criteria (with valid dimension filters):\n%s' % - report['criteria']) - - -def insert_report_resource(service, profile_id, report): - """Inserts the report.""" - inserted_report = service.reports().insert( - profileId=profile_id, body=report).execute() - - print('\nSuccessfully inserted new report with ID %s.' % - inserted_report['id']) - - return inserted_report - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_rotation_group.py b/python/v3_5/create_rotation_group.py deleted file mode 100644 index 8286711..0000000 --- a/python/v3_5/create_rotation_group.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a rotation group ad in a given campaign.""" - -import argparse -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a rotation group for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to add a rotation group for') -argparser.add_argument( - 'placement_id', type=int, - help='The ID of the placement to add a rotation group for') -argparser.add_argument( - 'creative_id', type=int, - help='The ID of the creative to add to the rotation group') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - placement_id = flags.placement_id - creative_id = flags.creative_id - - try: - # Retrieve the campaign (to get end date). - campaign = service.campaigns().get( - profileId=profile_id, id=campaign_id).execute() - - # Construct creative assignment. - creative_assignment = { - 'active': 'true', - 'creativeId': creative_id, - 'clickThroughUrl': { - 'defaultLandingPage': 'true' - } - } - - # Construct placement assignment. - placement_assignment = { - 'active': 'true', - 'placementId': placement_id, - } - - # Construct creative rotation. - creative_rotation = { - 'creativeAssignments': [creative_assignment], - 'type': 'CREATIVE_ROTATION_TYPE_RANDOM', - 'weightCalculationStrategy': 'WEIGHT_STRATEGY_OPTIMIZED' - } - - # Construct delivery schedule. - delivery_schedule = { - 'impressionRatio': '1', - 'priority': 'AD_PRIORITY_01' - } - - # Construct and save ad. - ad = { - 'active': 'true', - 'campaignId': campaign_id, - 'creativeRotation': creative_rotation, - 'deliverySchedule': delivery_schedule, - 'endTime': '%sT00:00:00Z' % campaign['endDate'], - 'name': 'Test Rotation Group', - 'placementAssignments': [placement_assignment], - 'startTime': '%sT23:59:59Z' % time.strftime('%Y-%m-%d'), - 'type': 'AD_SERVING_STANDARD_AD' - } - - request = service.ads().insert(profileId=profile_id, body=ad) - - # Execute request and print response. - response = request.execute() - - print ('Created rotation group with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_subaccount.py b/python/v3_5/create_subaccount.py deleted file mode 100755 index c463c68..0000000 --- a/python/v3_5/create_subaccount.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a subaccount in a given DFA account. - -To get the account ID, run get_all_userprofiles.py. To get the available -permissions, run get_user_role_permissions.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a subaccount for') -argparser.add_argument( - 'account_id', type=int, - help='The ID of the account to create a subaccount for') -argparser.add_argument( - 'permission_id', type=int, - help='The ID of the permission to apply to this subaccount') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - account_id = flags.account_id - permission_id = flags.permission_id - - try: - # Construct the basic subaccount structure. - subaccount = { - 'name': 'Test Subaccount', - 'accountId': account_id, - 'availablePermissionIds': [permission_id] - } - - request = service.subaccounts().insert( - profileId=profile_id, body=subaccount) - - # Execute request and print response. - response = request.execute() - - print ('Created subaccount with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_targeting_template.py b/python/v3_5/create_targeting_template.py deleted file mode 100644 index 16901c1..0000000 --- a/python/v3_5/create_targeting_template.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a targeting template associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys -import uuid - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a targeting template for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to add a targeting template for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct a basic targeting template. - # This template will be configured to serve ads on Monday, Wednesday, and - # Friday from 9-10am and 3-5pm. - # Note: targeting template names must be unique within an advetiser. - targeting_template = { - 'advertiserId': advertiser_id, - 'dayPartTargeting': { - 'daysOfWeek': ['MONDAY', 'WEDNESDAY', 'FRIDAY'], - 'hoursOfDay': [9, 15, 16], - 'userLocalTime': True - }, - 'name': 'Test Targeting Template #%s' % uuid.uuid4() - } - - request = service.targetingTemplates().insert(profileId=profile_id, - body=targeting_template) - - # Execute request and print response. - response = request.execute() - - print ('Created targeting template with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_tracking_creative.py b/python/v3_5/create_tracking_creative.py deleted file mode 100755 index 6bbc0a3..0000000 --- a/python/v3_5/create_tracking_creative.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a tracking creative associated with an advertiser.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to associate this creative with.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the basic creative structure. - creative = { - 'advertiserId': advertiser_id, - 'name': 'Test tracking creative', - 'type': 'TRACKING_TEXT' - } - - request = service.creatives().insert(profileId=profile_id, body=creative) - - # Execute request and print response. - response = request.execute() - - print ('Created tracking creative with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/create_user_role.py b/python/v3_5/create_user_role.py deleted file mode 100755 index 829cd34..0000000 --- a/python/v3_5/create_user_role.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example creates a user role in a given DFA account. - -To get the account ID, run get_all_userprofiles.py. To get the parent user role -ID, run get_user_roles.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a user role for') -argparser.add_argument( - 'account_id', type=int, - help='The ID of the subaccount to create a user role for') -argparser.add_argument( - 'parent_role_id', type=int, - help='The ID of the parent user role to assign to this user role') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - account_id = flags.account_id - parent_role_id = flags.parent_role_id - - try: - # Construct the basic user role structure. - user_role = { - 'name': 'Test User Role', - 'accountId': account_id, - 'parentUserRoleId': parent_role_id - } - - request = service.userRoles().insert(profileId=profile_id, body=user_role) - - # Execute request and print response. - response = request.execute() - - print ('Created user role with ID %s and name "%s".' - % (response['id'], response['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/delete_report.py b/python/v3_5/delete_report.py deleted file mode 100644 index 4f615b8..0000000 --- a/python/v3_5/delete_report.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to delete a report.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to delete a report for') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to delete') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Construct the request. - request = service.reports().delete(profileId=profile_id, reportId=report_id) - - # Execute request and print response. - request.execute() - - print 'Successfully deleted report with ID %s.' % report_id - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/dfareporting_utils.py b/python/v3_5/dfareporting_utils.py deleted file mode 100644 index 95c1f6c..0000000 --- a/python/v3_5/dfareporting_utils.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Handles common tasks across all API samples.""" - -import argparse -import os - -from googleapiclient import discovery -import httplib2 -from oauth2client import client -from oauth2client import file as oauthFile -from oauth2client import tools - - -API_NAME = 'dfareporting' -API_VERSION = 'v3.5' -API_SCOPES = ['https://www.googleapis.com/auth/dfareporting', - 'https://www.googleapis.com/auth/dfatrafficking', - 'https://www.googleapis.com/auth/ddmconversions'] - -# Filename used for the credential store. -CREDENTIAL_STORE_FILE = API_NAME + '.dat' - - -def get_arguments(argv, desc, parents=None): - """Validates and parses command line arguments. - - Args: - argv: list of strings, the command-line parameters of the application. - desc: string, a description of the sample being executed. - parents: list of argparse.ArgumentParser, additional command-line parsers. - - Returns: - The parsed command-line arguments. - """ - # Include the default oauth2client argparser - parent_parsers = [tools.argparser] - - if parents: - parent_parsers.extend(parents) - - parser = argparse.ArgumentParser( - description=desc, - formatter_class=argparse.RawDescriptionHelpFormatter, - parents=parent_parsers) - return parser.parse_args(argv[1:]) - - -def load_application_default_credentials(): - """Atempts to load application default credentials. - - Returns: - A credential object initialized with application default credentials or None - if none were found. - """ - try: - credentials = client.GoogleCredentials.get_application_default() - return credentials.create_scoped(API_SCOPES) - except client.ApplicationDefaultCredentialsError: - # No application default credentials, continue to try other options. - pass - - -def load_user_credentials(client_secrets, storage, flags): - """Attempts to load user credentials from the provided client secrets file. - - Args: - client_secrets: path to the file containing client secrets. - storage: the data store to use for caching credential information. - flags: command-line flags. - - Returns: - A credential object initialized with user account credentials. - """ - # Set up a Flow object to be used if we need to authenticate. - flow = client.flow_from_clientsecrets( - client_secrets, - scope=API_SCOPES, - message=tools.message_if_missing(client_secrets)) - - # Retrieve credentials from storage. - # If the credentials don't exist or are invalid run through the installed - # client flow. The storage object will ensure that if successful the good - # credentials will get written back to file. - credentials = storage.get() - if credentials is None or credentials.invalid: - credentials = tools.run_flow(flow, storage, flags) - - return credentials - - -def setup(flags): - """Handles authentication and loading of the API. - - Args: - flags: command-line flags obtained by calling ''get_arguments()''. - - Returns: - An initialized service object. - """ - # Load application default credentials if they're available. - credentials = load_application_default_credentials() - - # Otherwise, load credentials from the provided client secrets file. - if credentials is None: - # Name of a file containing the OAuth 2.0 information for this - # application, including client_id and client_secret, which are found - # on the Credentials tab on the Google Developers Console. - client_secrets = os.path.join(os.path.dirname(__file__), - 'client_secrets.json') - storage = oauthFile.Storage(CREDENTIAL_STORE_FILE) - credentials = load_user_credentials(client_secrets, storage, flags) - - # Authorize HTTP object with the prepared credentials. - http = credentials.authorize(http=httplib2.Http()) - - # Construct and return a service object via the discovery service. - return discovery.build(API_NAME, API_VERSION, http=http) diff --git a/python/v3_5/download_file.py b/python/v3_5/download_file.py deleted file mode 100644 index d529f51..0000000 --- a/python/v3_5/download_file.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to download a report file.""" - -import argparse -import io -import os -import sys - -import dfareporting_utils -from googleapiclient import http -from oauth2client import client - - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to get a file for') -argparser.add_argument( - 'file_id', type=int, - help='The ID of the file to get') - -# Chunk size to use when downloading report files. Defaults to 32MB. -CHUNK_SIZE = 32 * 1024 * 1024 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - report_id = flags.report_id - file_id = flags.file_id - - try: - # Retrieve the file metadata. - report_file = service.files().get(reportId=report_id, - fileId=file_id).execute() - - if report_file['status'] == 'REPORT_AVAILABLE': - # Prepare a local file to download the report contents to. - out_file = io.FileIO(generate_file_name(report_file), mode='wb') - - # Create a get request. - request = service.files().get_media(reportId=report_id, fileId=file_id) - - # Create a media downloader instance. - # Optional: adjust the chunk size used when downloading the file. - downloader = http.MediaIoBaseDownload(out_file, request, - chunksize=CHUNK_SIZE) - - # Execute the get request and download the file. - download_finished = False - while download_finished is False: - _, download_finished = downloader.next_chunk() - - print('File %s downloaded to %s' - % (report_file['id'], os.path.realpath(out_file.name))) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def generate_file_name(report_file): - """Generates a report file name based on the file metadata.""" - # If no filename is specified, use the file ID instead. - file_name = report_file['fileName'] or report_file['id'] - extension = '.csv' if report_file['format'] == 'CSV' else '.xml' - return file_name + extension - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/download_floodlight_tag.py b/python/v3_5/download_floodlight_tag.py deleted file mode 100644 index 835289e..0000000 --- a/python/v3_5/download_floodlight_tag.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example downloads activity tags for a given floodlight activity.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to download tags for') -argparser.add_argument( - 'activity_id', - type=int, - help='The ID of the floodlight activity to download tags for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - activity_id = flags.activity_id - - try: - # Construct the request. - request = service.floodlightActivities().generatetag( - profileId=profile_id, floodlightActivityId=activity_id) - - # Execute request and print response. - response = request.execute() - - if 'globalSiteTagGlobalSnippet' in response: - # Print both global snippet and event snippet. - print('Global site tag global snippet:\n\n%s' % - response['globalSiteTagGlobalSnippet']) - print('\n\nGlobal site tag event snippet:\n\n%s' % - response['floodlightActivityTag']) - else: - # Print the Floodlight activity tag. - print('Floodlight activity tag:\n\n%s' % - response['floodlightActivityTag']) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/download_placement_tags.py b/python/v3_5/download_placement_tags.py deleted file mode 100644 index 57ca8cb..0000000 --- a/python/v3_5/download_placement_tags.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example downloads HTML Tags for a given campaign and placement ID. - -To create campaigns, run create_campaign.py. To create placements, run -create_placement.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to download tags for') -argparser.add_argument( - 'campaign_id', type=int, - help='The ID of the campaign to download tags for') -argparser.add_argument( - 'placement_id', type=int, - help='The ID of the placement to download tags for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - campaign_id = flags.campaign_id - placement_id = flags.placement_id - - try: - # Construct the request. - request = service.placements().generatetags( - profileId=profile_id, campaignId=campaign_id, - placementIds=[placement_id]) - - # Execute request and print response. - response = request.execute() - - for placement_tag in response['placementTags']: - print_placement_tag(placement_tag) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def print_placement_tag(placement_tag): - for tag_data in placement_tag['tagDatas']: - print ('%s - %s\n' - % (placement_tag['placementId'], tag_data['format'])) - - if 'impressionTag' in tag_data: - print '%s\n\n' % (tag_data['impressionTag']) - if 'clickTag' in tag_data: - print '%s\n\n' % (tag_data['clickTag']) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/find_and_download_file.py b/python/v3_5/find_and_download_file.py deleted file mode 100644 index 552e4d5..0000000 --- a/python/v3_5/find_and_download_file.py +++ /dev/null @@ -1,149 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""An end-to-end example of how to find and download a report file.""" - -import argparse -import io -import os -import sys - -import dfareporting_utils -from googleapiclient import http -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, help='The ID of the report to get a file for') - -# Chunk size to use when downloading report files. Defaults to 32MB. -CHUNK_SIZE = 32 * 1024 * 1024 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # 1. Find a file to download. - report_file = find_file(service, profile_id, report_id) - - if report_file: - # 2. (optional) Generate browser URL. - generate_browser_url(service, report_id, report_file['id']) - - # 3. Directly download the file. - direct_download_file(service, report_id, report_file['id']) - else: - print 'No file found for profile ID %d and report ID %d.' % (profile_id, - report_id) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def find_file(service, profile_id, report_id): - """Finds a report file to download.""" - target = None - - request = service.reports().files().list( - profileId=profile_id, reportId=report_id) - - while True: - response = request.execute() - - for report_file in response['items']: - if is_target_file(report_file): - target = report_file - break - - if not target and response['items'] and response['nextPageToken']: - request = service.reports().files().list_next(request, response) - else: - break - - if target: - print 'Found file %s with filename "%s".' % (target['id'], - target['fileName']) - return target - - print 'Unable to find file for profile ID %d and report ID %d.' % (profile_id, - report_id) - return None - - -def is_target_file(report_file): - # Provide custom validation logic here. - # For example purposes, any available file is considered valid. - return report_file['status'] == 'REPORT_AVAILABLE' - - -def generate_browser_url(service, report_id, file_id): - """Prints the browser download URL for the file.""" - report_file = service.files().get( - reportId=report_id, fileId=file_id).execute() - browser_url = report_file['urls']['browserUrl'] - - print 'File %s has browser URL: %s.' % (report_file['id'], browser_url) - - -def direct_download_file(service, report_id, file_id): - """Downloads a report file to disk.""" - # Retrieve the file metadata. - report_file = service.files().get( - reportId=report_id, fileId=file_id).execute() - - if report_file['status'] == 'REPORT_AVAILABLE': - # Prepare a local file to download the report contents to. - out_file = io.FileIO(generate_file_name(report_file), mode='wb') - - # Create a get request. - request = service.files().get_media(reportId=report_id, fileId=file_id) - - # Create a media downloader instance. - # Optional: adjust the chunk size used when downloading the file. - downloader = http.MediaIoBaseDownload( - out_file, request, chunksize=CHUNK_SIZE) - - # Execute the get request and download the file. - download_finished = False - while download_finished is False: - _, download_finished = downloader.next_chunk() - - print('File %s downloaded to %s' % (report_file['id'], - os.path.realpath(out_file.name))) - - -def generate_file_name(report_file): - """Generates a report file name based on the file metadata.""" - # If no filename is specified, use the file ID instead. - file_name = report_file['fileName'] or report_file['id'] - extension = '.csv' if report_file['format'] == 'CSV' else '.xml' - return file_name + extension - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/find_and_run_report.py b/python/v3_5/find_and_run_report.py deleted file mode 100644 index 208bfd6..0000000 --- a/python/v3_5/find_and_run_report.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""An end-to-end example of how to find and run a report.""" - -import argparse -import random -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to use') - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # 1. Find a report to run. - report = find_report(service, profile_id) - - if report: - # 2. Run the report. - report_file = run_report(service, profile_id, report['id']) - - # 3. Wait for the report file to be ready. - wait_for_report_file(service, report['id'], report_file['id']) - else: - print 'No report found for profile ID %d.\n' % profile_id - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def find_report(service, profile_id): - """Finds a report to run.""" - target = None - - # Construct the request. - request = service.reports().list(profileId=profile_id) - - while True: - response = request.execute() - - for report in response['items']: - if is_target_report(report): - target = report - break - - if not target and response['items'] and response['nextPageToken']: - request = service.reports().list_next(request, response) - else: - break - - if target: - print 'Found report %s with name "%s".' % (target['id'], target['name']) - return target - - print 'Unable to find report for profile ID %d.' % profile_id - return None - - -def is_target_report(report): - # Provide custom validation logic here. - # For example purposes, any report is considered valid. - return report is not None - - -def run_report(service, profile_id, report_id): - """Runs the report.""" - # Run the report. - report_file = service.reports().run( - profileId=profile_id, reportId=report_id).execute() - - print 'Running report %s, current file status is %s.' % ( - report_id, report_file['status']) - return report_file - - -def wait_for_report_file(service, report_id, file_id): - """Waits for the report file to finish processing.""" - # Wait for the report file to finish processing. - # An exponential backoff strategy is used to conserve request quota. - sleep = 0 - start_time = time.time() - while True: - report_file = service.files().get( - reportId=report_id, fileId=file_id).execute() - - status = report_file['status'] - if status == 'REPORT_AVAILABLE': - print 'File status is %s, ready to download.' % status - return - elif status != 'PROCESSING': - print 'File status is %s, processing failed.' % status - return - elif time.time() - start_time > MAX_RETRY_ELAPSED_TIME: - print 'File processing deadline exceeded.' - return - - sleep = next_sleep_interval(sleep) - print 'File status is %s, sleeping for %d seconds.' % (status, sleep) - time.sleep(sleep) - - -def next_sleep_interval(previous_sleep_interval): - """Calculates the next sleep interval based on the previous.""" - min_interval = previous_sleep_interval or MIN_RETRY_INTERVAL - max_interval = previous_sleep_interval * 3 or MIN_RETRY_INTERVAL - return min(MAX_RETRY_INTERVAL, random.randint(min_interval, max_interval)) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_ads.py b/python/v3_5/get_ads.py deleted file mode 100755 index a7d38ee..0000000 --- a/python/v3_5/get_ads.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all active ads your DFA user profile can see. - -Only name and ID are returned. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up ads for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.ads().list(profileId=profile_id, active=True) - - while True: - # Execute request and print response. - response = request.execute() - - for ad in response['ads']: - print 'Found ad with ID %s and name "%s".' % (ad['id'], ad['name']) - - if response['ads'] and response['nextPageToken']: - request = service.ads().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_advertiser_groups.py b/python/v3_5/get_advertiser_groups.py deleted file mode 100644 index c69c636..0000000 --- a/python/v3_5/get_advertiser_groups.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all advertiser groups for a specified user profile.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list activity groups for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.advertiserGroups().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for group in response['advertiserGroups']: - print ('Found advertiser group with ID %s and name "%s".' - % (group['id'], group['name'])) - - if response['advertiserGroups'] and response['nextPageToken']: - request = service.advertiserGroups().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_advertiser_landing_pages.py b/python/v3_5/get_advertiser_landing_pages.py deleted file mode 100644 index d183979..0000000 --- a/python/v3_5/get_advertiser_landing_pages.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all landing pages for the specified advertiser.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to look up advertiser landing pages for') -argparser.add_argument( - 'advertiser_id', - type=int, - help='The ID of the advertiser to look up landing pages for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.advertiserLandingPages().list( - profileId=profile_id, advertiserIds=[advertiser_id]) - - while True: - # Execute request and print response. - response = request.execute() - - for landing_page in response['landingPages']: - print('Found advertiser landing page with ID %s and name "%s".' % - (landing_page['id'], landing_page['name'])) - - if response['landingPages'] and response['nextPageToken']: - request = service.advertiserLandingPages().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_advertisers.py b/python/v3_5/get_advertisers.py deleted file mode 100755 index dffc246..0000000 --- a/python/v3_5/get_advertisers.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all advertisers. - -Only advertiser name, ID and floodlight config ID will be returned. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up advertisers for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.advertisers().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for advertiser in response['advertisers']: - print ('Found advertiser with ID %s and name "%s".' - % (advertiser['id'], advertiser['name'])) - - if response['advertisers'] and response['nextPageToken']: - request = service.advertisers().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_campaigns.py b/python/v3_5/get_campaigns.py deleted file mode 100644 index 28b471a..0000000 --- a/python/v3_5/get_campaigns.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all existing campaigns for the specified user profile.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up campaigns for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.campaigns().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for campaign in response['campaigns']: - print ('Found campaign with ID %s and name "%s".' - % (campaign['id'], campaign['name'])) - - if response['campaigns'] and response['nextPageToken']: - request = service.campaigns().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_change_logs_for_advertiser.py b/python/v3_5/get_change_logs_for_advertiser.py deleted file mode 100644 index 6fa696a..0000000 --- a/python/v3_5/get_change_logs_for_advertiser.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays the change logs of a specified advertiser object. - -A similar pattern can be applied to get change logs for many other object -types. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up change logs for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to look up change logs for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.changeLogs().list( - profileId=profile_id, objectIds=[advertiser_id], - objectType='OBJECT_ADVERTISER') - - while True: - # Execute request and print response. - response = request.execute() - - for change_log in response['changeLogs']: - print( - '%s: Field "%s" from "%s" to "%s".' % - (change_log['action'], change_log['fieldName'], - change_log['oldValue'], change_log['newValue'])) - - if response['changeLogs'] and response['nextPageToken']: - request = service.changeLogs().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_compatible_fields.py b/python/v3_5/get_compatible_fields.py deleted file mode 100644 index 22fcf00..0000000 --- a/python/v3_5/get_compatible_fields.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get the compatible fields for a report.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to get compatible fields for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Retrieve the specified report resource - report = service.reports().get( - profileId=profile_id, reportId=report_id).execute() - - compatible_fields_type = get_compatible_fields_type(report['type']) - - # Construct the request - request = service.reports().compatibleFields().query( - profileId=profile_id, body=report) - - # Execute the request and print response. - response = request.execute() - - compatible_fields = response[compatible_fields_type] - print_fields('Dimensions', compatible_fields['dimensions']) - print_fields('Metrics', compatible_fields['metrics']) - print_fields('Dimension Filters', - compatible_fields['dimensionFilters']) - print_fields('Pivoted Activity Metrics', - compatible_fields['pivotedActivityMetrics']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def get_compatible_fields_type(report_type): - return { - 'CROSS_DIMENSION_REACH': 'crossDimensionReachReportCompatibleFields', - 'FLOODLIGHT': 'floodlightReportCompatibleFields', - 'PATH_TO_CONVERSION': 'pathToConversionReportCompatibleFields', - 'REACH': 'reachReportCompatibleFields' - }.get(report_type, 'reportCompatibleFields') - - -def print_fields(field_type, fields): - field_names = [field['name'] for field in fields] - print 'Compatible %s\n%s\n\n' % (field_type, ','.join(field_names)) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_content_categories.py b/python/v3_5/get_content_categories.py deleted file mode 100644 index 2300efd..0000000 --- a/python/v3_5/get_content_categories.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all available content categories.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up content categories for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.contentCategories().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for category in response['contentCategories']: - print ('Found content category with ID %s and name "%s".' - % (category['id'], category['name'])) - - if response['contentCategories'] and response['nextPageToken']: - request = service.contentCategories().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_creative_field_values.py b/python/v3_5/get_creative_field_values.py deleted file mode 100644 index c8cd19c..0000000 --- a/python/v3_5/get_creative_field_values.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all creative fields.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get creative field values for') -argparser.add_argument( - 'field_id', type=int, - help='The ID of the creative field to get values for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - field_id = flags.field_id - - try: - # Construct the request. - request = service.creativeFieldValues().list( - profileId=profile_id, creativeFieldId=field_id) - - while True: - # Execute request and print response. - response = request.execute() - - for value in response['creativeFieldValues']: - print ('Found creative field value with ID %s and value "%s".' - % (value['id'], value['value'])) - - if response['creativeFieldValues'] and response['nextPageToken']: - request = service.creativeFieldValues().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_creative_fields.py b/python/v3_5/get_creative_fields.py deleted file mode 100644 index 7493dfd..0000000 --- a/python/v3_5/get_creative_fields.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all creative fields.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get creative fields for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.creativeFields().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for field in response['creativeFields']: - print ('Found creative field with ID %s and name "%s".' - % (field['id'], field['name'])) - - if response['creativeFields'] and response['nextPageToken']: - request = service.creativeFields().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_creative_groups.py b/python/v3_5/get_creative_groups.py deleted file mode 100644 index 6a39896..0000000 --- a/python/v3_5/get_creative_groups.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all creative groups.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get creative groups for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.creativeGroups().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for group in response['creativeGroups']: - print ('Found creative group with ID %s and name "%s".' - % (group['id'], group['name'])) - - if response['creativeGroups'] and response['nextPageToken']: - request = service.advertisers().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_creatives.py b/python/v3_5/get_creatives.py deleted file mode 100644 index 0d97fed..0000000 --- a/python/v3_5/get_creatives.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all existing active creatives for a given advertiser. - -To get an advertiser ID, run get_advertisers.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up creatives for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to look up creatives for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.creatives().list( - profileId=profile_id, active=True, advertiserId=advertiser_id) - - while True: - # Execute request and print response. - response = request.execute() - - for creative in response['creatives']: - print ('Found %s creative with ID %s and name "%s".' - % (creative['type'], creative['id'], creative['name'])) - - if response['creatives'] and response['nextPageToken']: - request = service.creatives().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_dimension_values.py b/python/v3_5/get_dimension_values.py deleted file mode 100644 index f17f3ee..0000000 --- a/python/v3_5/get_dimension_values.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get all dimension values for a dimension.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to get a report for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Create the dimension to query - dimension = { - 'dimensionName': 'advertiser', - 'startDate': '2012-01-01', - 'endDate': '2013-12-31' - } - - # Construct the request. - request = service.dimensionValues().query( - profileId=profile_id, body=dimension) - - while True: - # Execute request and print response. - response = request.execute() - - for value in response['items']: - print ('Found dimension value with ID %s and value "%s".' - % (value['id'], value['value'])) - - if response['items'] and response['nextPageToken']: - request = service.dimensionValues().query_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_files.py b/python/v3_5/get_files.py deleted file mode 100644 index c2c96ad..0000000 --- a/python/v3_5/get_files.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all the files for a profile.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct a get request for the specified profile. - request = service.files().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for report_file in response['items']: - print ('File with ID %s and file name "%s" has status "%s".' - % (report_file['id'], report_file['fileName'], - report_file['status'])) - - if response['items'] and response['nextPageToken']: - request = service.files().list_next(request, response) - else: - break - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_floodlight_activities.py b/python/v3_5/get_floodlight_activities.py deleted file mode 100644 index c7ffa6f..0000000 --- a/python/v3_5/get_floodlight_activities.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays floodlight activities for a given advertiser. - -To create an advertiser, run create_advertiser.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list activities for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to list activities for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.floodlightActivities().list( - profileId=profile_id, advertiserId=advertiser_id) - - while True: - # Execute request and print response. - response = request.execute() - - for activity in response['floodlightActivities']: - print ('Found floodlight activity with ID %s and name "%s".' - % (activity['id'], activity['name'])) - - if response['floodlightActivities'] and response['nextPageToken']: - request = service.floodlightActivities().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_floodlight_activity_groups.py b/python/v3_5/get_floodlight_activity_groups.py deleted file mode 100644 index ac17db7..0000000 --- a/python/v3_5/get_floodlight_activity_groups.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays floodlight activity groups for a given advertiser. - -To create an advertiser, run create_advertiser.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list activity groups for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to list activity groups for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.floodlightActivityGroups().list( - profileId=profile_id, advertiserId=advertiser_id) - - # Execute request and print response. - response = request.execute() - - for group in response['floodlightActivityGroups']: - print ('Found floodlight activity group with ID %s and name "%s".' - % (group['id'], group['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_placement_strategies.py b/python/v3_5/get_placement_strategies.py deleted file mode 100644 index 3999316..0000000 --- a/python/v3_5/get_placement_strategies.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all available placement strategies.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up placement strategies for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.placementStrategies().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for strategy in response['placementStrategies']: - print ('Found placement strategy with ID %s and name "%s".' - % (strategy['id'], strategy['name'])) - - if response['placementStrategies'] and response['nextPageToken']: - request = service.placementStrategies().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_placements.py b/python/v3_5/get_placements.py deleted file mode 100644 index 909d01e..0000000 --- a/python/v3_5/get_placements.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all available placements.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up placements for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.placements().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for placement in response['placements']: - print ('Found placement with ID %s and name "%s" for campaign "%s".' - % (placement['id'], placement['name'], - placement['campaignId'])) - - if response['placements'] and response['nextPageToken']: - request = service.placements().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_remarketing_lists.py b/python/v3_5/get_remarketing_lists.py deleted file mode 100644 index 59ee99b..0000000 --- a/python/v3_5/get_remarketing_lists.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Displays all remarketing lists owned by the specified advertiser. - -Note: the RemarketingLists resource will only return lists owned by the -specified advertiser. To see all lists that can be used for targeting ads -(including those shared from other accounts or advertisers), use the -TargetableRemarketingLists resource instead. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up remarketing lists for') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to look up remarketing lists for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = flags.advertiser_id - - try: - # Construct the request. - request = service.remarketingLists().list( - profileId=profile_id, advertiserId=advertiser_id) - - while True: - # Execute request and print response. - response = request.execute() - - for remarketing_list in response['remarketingLists']: - print ('Found remarketing list with ID %s and name "%s."' - % (remarketing_list['id'], remarketing_list['name'])) - - if response['remarketingLists'] and response['nextPageToken']: - request = service.remarketingLists().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_report_files.py b/python/v3_5/get_report_files.py deleted file mode 100644 index f7b839d..0000000 --- a/python/v3_5/get_report_files.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all the files for a report.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to list files for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Construct a get request for the specified report. - request = service.reports().files().list( - profileId=profile_id, reportId=report_id) - - while True: - # Execute request and print response. - response = request.execute() - - for report_file in response['items']: - print ('Report file with ID %s and file name "%s" has status %s.' - % (report_file['id'], report_file['fileName'], - report_file['status'])) - - if response['items'] and response['nextPageToken']: - request = service.reports().files().list_next(request, response) - else: - break - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_reports.py b/python/v3_5/get_reports.py deleted file mode 100644 index 3c15b95..0000000 --- a/python/v3_5/get_reports.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all reports.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list reports for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.reports().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for report in response['items']: - print ('Found %s report with ID %s and name "%s".' - % (report['type'], report['id'], report['name'])) - - if response['items'] and response['nextPageToken']: - request = service.reports().list_next(request, response) - else: - break - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_sites.py b/python/v3_5/get_sites.py deleted file mode 100644 index b3720e5..0000000 --- a/python/v3_5/get_sites.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example lists all existing sites.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sites for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.sites().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for site in response['sites']: - print ('Found site with ID %s and key name "%s".' - % (site['id'], site['keyName'])) - - if response['sites'] and response['nextPageToken']: - request = service.sites().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_size.py b/python/v3_5/get_size.py deleted file mode 100644 index a09f47a..0000000 --- a/python/v3_5/get_size.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all sizes for a given width and height.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sizes for') -argparser.add_argument( - 'height', type=int, - help='Width of the size to look up') -argparser.add_argument( - 'width', type=int, - help='Height of the size to look up') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - height = flags.height - width = flags.width - - try: - # Construct the request. - request = service.sizes().list( - profileId=profile_id, height=height, width=width) - - # Execute request and print response. - result = request.execute() - - for size in result['sizes']: - print 'Found size with ID %s.' % (size['id']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_subaccounts.py b/python/v3_5/get_subaccounts.py deleted file mode 100644 index d1f4c9b..0000000 --- a/python/v3_5/get_subaccounts.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all subaccounts. - -Note that the permissions assigned to a subaccount are not returned in a -human-readable format with this example. Run get_available_permissions.py to -see what permissions are available on a subaccount. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sites for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Construct the request. - request = service.subaccounts().list(profileId=profile_id) - - while True: - # Execute request and print response. - response = request.execute() - - for subaccount in response['subaccounts']: - print ('Found subaccount with ID %s and name "%s".' - % (subaccount['id'], subaccount['name'])) - - if response['subaccounts'] and response['nextPageToken']: - request = service.subaccounts().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_targeting_templates.py b/python/v3_5/get_targeting_templates.py deleted file mode 100644 index a138fc8..0000000 --- a/python/v3_5/get_targeting_templates.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example retrieves all targeting templates for your DCM user profile. - -Displays name, ID, and advertiser ID for each targeting template found. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up targeting templates for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Limit the fields returned - fields = 'nextPageToken,targetingTemplates(advertiserId,id,name)' - - # Construct the request. - request = service.targetingTemplates().list(profileId=profile_id, - fields=fields) - - while True: - # Execute request and print response. - response = request.execute() - - for template in response['targetingTemplates']: - print ('Found targeting template with ID %s and name "%s" associated ' - 'with advertiser ID %s.' % (template['id'], template['name'], - template['advertiserId'])) - - if response['targetingTemplates'] and response['nextPageToken']: - request = service.targetingTemplates().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_user_role_permissions.py b/python/v3_5/get_user_role_permissions.py deleted file mode 100644 index 8ad2a02..0000000 --- a/python/v3_5/get_user_role_permissions.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all of the available subaccount permissions. - -To get a subaccount ID, run get_subaccounts.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to list permissions for') -argparser.add_argument( - 'subaccount_id', type=int, - help='The ID of the subaccount to list permissions for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - subaccount_id = flags.subaccount_id - - try: - # Construct and execute the subaccount request. - request = service.subaccounts().get( - profileId=profile_id, id=subaccount_id) - - subaccount = request.execute() - - # Construct the user role permissions request. - request = service.userRolePermissions().list( - profileId=profile_id, ids=subaccount['availablePermissionIds']) - - # Execute request and print response. - result = request.execute() - - for permission in result['userRolePermissions']: - print ('Found user role permission with ID %s and name "%s".' - % (permission['id'], permission['name'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_user_roles.py b/python/v3_5/get_user_roles.py deleted file mode 100644 index cb78b36..0000000 --- a/python/v3_5/get_user_roles.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example displays all user roles. - -The output is limited to include only ID, name, account ID and subaccount ID. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to look up sites for') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - - try: - # Limit the fields returned - fields = 'nextPageToken,userRoles(accountId,id,name,subaccountId)' - - # Construct the request. - request = service.userRoles().list(profileId=profile_id, fields=fields) - - while True: - # Execute request and print response. - response = request.execute() - - for user_role in response['userRoles']: - print ('Found user role with ID %s and name "%s".' - % (user_role['id'], user_role['name'])) - - if response['userRoles'] and response['nextPageToken']: - request = service.userRoles().list_next(request, response) - else: - break - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/get_userprofiles.py b/python/v3_5/get_userprofiles.py deleted file mode 100644 index d029d85..0000000 --- a/python/v3_5/get_userprofiles.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to get a list of all user profiles.""" - -import sys - -import dfareporting_utils -from oauth2client import client - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - try: - # Construct the request. - request = service.userProfiles().list() - - # Execute request and print response. - response = request.execute() - - for profile in response['items']: - print ('Found user profile with ID %s and name "%s" for account %s.' - % (profile['profileId'], profile['userName'], - profile['accountId'])) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/insert_offline_mobile_conversion.py b/python/v3_5/insert_offline_mobile_conversion.py deleted file mode 100644 index d659e0d..0000000 --- a/python/v3_5/insert_offline_mobile_conversion.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Inserts an offline conversion attributed to a mobile device ID.""" - -import argparse -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'mobile_device_id', - help='The ID of the mobile device to attribute the conversion to') -argparser.add_argument( - 'floodlight_activity_id', type=int, - help='The ID of Floodlight activity this conversion is associated with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - floodlight_activity_id = flags.floodlight_activity_id - mobile_device_id = flags.mobile_device_id - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - current_time_in_micros = int(time.time() * 1000000) - - # Construct the conversion. - conversion = { - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': current_time_in_micros, - 'mobileDeviceId': mobile_device_id, - 'timestampMicros': current_time_in_micros - } - - # Insert the conversion. - request_body = {'conversions': [conversion]} - request = service.conversions().batchinsert(profileId=profile_id, - body=request_body) - response = request.execute() - - if not response['hasFailures']: - print ('Successfully inserted conversion for mobile device ID %s.' - % mobile_device_id) - else: - print ('Error(s) inserting conversion for mobile device ID %s.' - % mobile_device_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/insert_offline_user_conversion.py b/python/v3_5/insert_offline_user_conversion.py deleted file mode 100644 index 974c3f1..0000000 --- a/python/v3_5/insert_offline_user_conversion.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Inserts an offline conversion attributed to an encrypted user ID.""" - -import argparse -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to add a placement for') -argparser.add_argument( - 'encrypted_user_id', - help='The encrypted user ID to attribute the conversion to') -argparser.add_argument( - 'encryption_source', - help='The source of the encrypted user ID') -argparser.add_argument( - 'encryption_entity_id', type=int, - help='The ID of the entity used to encrypt the supplied user ID') -argparser.add_argument( - 'encryption_entity_type', - help='The type of the entity used to encrypt the supplied user ID') -argparser.add_argument( - 'floodlight_activity_id', type=int, - help='The ID of Floodlight activity this conversion is associated with') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - encrypted_user_id = flags.encrypted_user_id - encryption_entity_id = flags.encryption_entity_id - encryption_entity_type = flags.encryption_entity_type - encryption_source = flags.encryption_source - floodlight_activity_id = flags.floodlight_activity_id - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - current_time_in_micros = int(time.time() * 1000000) - - # Construct the conversion. - conversion = { - 'encryptedUserId': encrypted_user_id, - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': current_time_in_micros, - 'timestampMicros': current_time_in_micros - } - - # Construct the encryption info. - encryption_info = { - 'encryptionEntityId': encryption_entity_id, - 'encryptionEntityType': encryption_entity_type, - 'encryptionSource': encryption_source - } - - # Insert the conversion. - request_body = { - 'conversions': [conversion], - 'encryptionInfo': encryption_info - } - request = service.conversions().batchinsert(profileId=profile_id, - body=request_body) - response = request.execute() - - if not response['hasFailures']: - print ('Successfully inserted conversion for encrypted user ID %s.' - % encrypted_user_id) - else: - print ('Error(s) inserting conversion for encrypted user ID %s.' - % encrypted_user_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/run_report.py b/python/v3_5/run_report.py deleted file mode 100644 index cc83059..0000000 --- a/python/v3_5/run_report.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example illustrates how to run a report.""" - -import argparse -import random -import sys -import time - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to use') -argparser.add_argument( - 'report_id', type=int, - help='The ID of the report to run') - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - report_id = flags.report_id - - try: - # Run the report. - report_file = service.reports().run(profileId=profile_id, - reportId=report_id).execute() - print 'File with ID %s has been created.' % report_file['id'] - - # Wait for the report file to finish processing. - # An exponential backoff strategy is used to conserve request quota. - sleep = 0 - start_time = time.time() - while True: - report_file = service.files().get(reportId=report_id, - fileId=report_file['id']).execute() - - status = report_file['status'] - if status == 'REPORT_AVAILABLE': - print 'File status is %s, ready to download.' % status - return - elif status != 'PROCESSING': - print 'File status is %s, processing failed.' % status - return - elif time.time() - start_time > MAX_RETRY_ELAPSED_TIME: - print 'File processing deadline exceeded.' - return - - sleep = next_sleep_interval(sleep) - print 'File status is %s, sleeping for %d seconds.' % (status, sleep) - time.sleep(sleep) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -def next_sleep_interval(previous_sleep_interval): - """Calculates the next sleep interval based on the previous.""" - min_interval = previous_sleep_interval or MIN_RETRY_INTERVAL - max_interval = previous_sleep_interval * 3 or MIN_RETRY_INTERVAL - return min(MAX_RETRY_INTERVAL, random.randint(min_interval, max_interval)) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/share_remarketing_list_to_advertiser.py b/python/v3_5/share_remarketing_list_to_advertiser.py deleted file mode 100644 index 964bfc4..0000000 --- a/python/v3_5/share_remarketing_list_to_advertiser.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Shares an existing remarketing list with the specified advertiser.""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, - help='The ID of the profile to share remarketing lists as') -argparser.add_argument( - 'advertiser_id', type=int, - help='The ID of the advertiser to share the remarketing list with') -argparser.add_argument( - 'remarketing_list_id', type=int, - help='The ID of the remarketing list to share') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - advertiser_id = str(flags.advertiser_id) - list_id = flags.remarketing_list_id - - try: - # Load the existing share info. - share = service.remarketingListShares().get( - profileId=profile_id, remarketingListId=list_id).execute() - - share['sharedAdvertiserIds'] = share.get('sharedAdvertiserIds', []) - - if advertiser_id not in share['sharedAdvertiserIds']: - share['sharedAdvertiserIds'].append(advertiser_id) - - # Update the share info with the newly added advertiser ID. - response = service.remarketingListShares().update( - profileId=profile_id, body=share).execute() - - print ('Remarketing list %s is now shared to advertiser ID(s): %s.' - % (list_id, ','.join(response['sharedAdvertiserIds']))) - else: - print ('Remarketing list %s is already shared to advertiser %s' - % (list_id, advertiser_id)) - - except client.AccessTokenRefreshError: - print ('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/target_ad_to_remarketing_list.py b/python/v3_5/target_ad_to_remarketing_list.py deleted file mode 100644 index 658e252..0000000 --- a/python/v3_5/target_ad_to_remarketing_list.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This example targets an ad to a remarketing list. - -The first targetable remarketing list, either owned by or shared to the ad's -advertiser, will be used. To create a remarketing list, see -create_remarketing_list.py. To share a remarketing list with the ad's -advertiser, see share_remarketing_list_to_advertiser.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', type=int, help='The ID of the profile to use for targeting') -argparser.add_argument('ad_id', type=int, help='The ID of the ad to target') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - ad_id = flags.ad_id - - try: - # Retrieve the ad. - ad = service.ads().get(profileId=profile_id, id=ad_id).execute() - - # Retrieve a single targetable remarketing list for the ad. - lists = service.targetableRemarketingLists().list( - profileId=profile_id, advertiserId=ad['advertiserId'], - maxResults=1).execute() - - if lists['targetableRemarketingLists']: - remarketing_list = lists['targetableRemarketingLists'][0] - - # Update the ad with a list targeting expression - ad['remarketingListExpression'] = { - 'expression': remarketing_list['id'] - } - response = service.ads().update(profileId=profile_id, body=ad).execute() - - print('Ad %s updated to use remarketing list expression: "%s".' - % (response['id'], - response['remarketingListExpression']['expression'])) - else: - print 'No targetable remarketing lists found for ad with ID %d.' % ad_id - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/update_offline_mobile_conversion.py b/python/v3_5/update_offline_mobile_conversion.py deleted file mode 100644 index 9fd2736..0000000 --- a/python/v3_5/update_offline_mobile_conversion.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Updates an offline conversion attributed to a mobile device ID. - -To create a conversion attributed to a mobile device ID, run -insert_offline_mobile_conversion.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to update a conversion for') - -# Values that identify the existing conversion. -argparser.add_argument( - 'mobile_device_id', - help='The ID of the mobile device the conversion is attributed to.') -argparser.add_argument( - 'floodlight_activity_id', - type=int, - help='The ID of Floodlight activity the conversion is associated with') -argparser.add_argument('ordinal', help='The ordinal of the conversion.') -argparser.add_argument( - 'timestamp', type=int, help='The timestamp of the conversion.') - -# Values to update for the specified conversion. -argparser.add_argument( - 'new_quantity', - type=int, - help='The new quantity to set for the conversion.') -argparser.add_argument( - 'new_value', type=int, help='The new value to set for the conversion.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - floodlight_activity_id = flags.floodlight_activity_id - mobile_device_id = flags.mobile_device_id - ordinal = flags.ordinal - timestamp = flags.timestamp - new_quantity = flags.new_quantity - new_value = flags.new_value - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - # Construct the conversion object with values that identify the conversion - # to update. - conversion = { - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': ordinal, - 'mobileDeviceId': mobile_device_id, - 'timestampMicros': timestamp - } - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion['quantity'] = new_quantity - conversion['value'] = new_value - - # Update the conversion. - request_body = {'conversions': [conversion]} - request = service.conversions().batchupdate( - profileId=profile_id, body=request_body) - response = request.execute() - - if not response['hasFailures']: - print('Successfully updated conversion for mobile device ID %s.' % - mobile_device_id) - else: - print('Error(s) updating conversion for mobile device ID %s.' % - mobile_device_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/python/v3_5/update_offline_user_conversion.py b/python/v3_5/update_offline_user_conversion.py deleted file mode 100644 index e7b9fff..0000000 --- a/python/v3_5/update_offline_user_conversion.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Updates an offline conversion attributed to an encrypted user ID. - -To create a conversion attributed to an encrypted user ID, run -insert_offline_user_conversion.py. -""" - -import argparse -import sys - -import dfareporting_utils -from oauth2client import client - -# Declare command-line flags. -argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument( - 'profile_id', - type=int, - help='The ID of the profile to update a conversion for') - -# Values that specify how the existing conversion is encrypted. -argparser.add_argument( - 'encrypted_user_id', - help='The encrypted user ID the conversion is attributed to') -argparser.add_argument( - 'encryption_source', help='The source of the encrypted user ID') -argparser.add_argument( - 'encryption_entity_id', - type=int, - help='The ID of the entity used to encrypt the supplied user ID') -argparser.add_argument( - 'encryption_entity_type', - help='The type of the entity used to encrypt the supplied user ID') - -# Values that identify the existing conversion. -argparser.add_argument( - 'floodlight_activity_id', - type=int, - help='The ID of Floodlight activity this conversion is associated with') -argparser.add_argument('ordinal', help='The ordinal of the conversion.') -argparser.add_argument( - 'timestamp', type=int, help='The timestamp of the conversion.') - -# Values to update for the specified conversion. -argparser.add_argument( - 'new_quantity', - type=int, - help='The new quantity to set for the conversion.') -argparser.add_argument( - 'new_value', type=int, help='The new value to set for the conversion.') - - -def main(argv): - # Retrieve command line arguments. - flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser]) - - # Authenticate and construct service. - service = dfareporting_utils.setup(flags) - - profile_id = flags.profile_id - encrypted_user_id = flags.encrypted_user_id - encryption_entity_id = flags.encryption_entity_id - encryption_entity_type = flags.encryption_entity_type - encryption_source = flags.encryption_source - floodlight_activity_id = flags.floodlight_activity_id - ordinal = flags.ordinal - timestamp = flags.timestamp - new_quantity = flags.new_quantity - new_value = flags.new_value - - try: - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.floodlightActivities().get( - profileId=profile_id, id=floodlight_activity_id).execute() - floodlight_config_id = floodlight_activity['floodlightConfigurationId'] - - # Construct the conversion object with values that identify the conversion - # to update. - conversion = { - 'encryptedUserId': encrypted_user_id, - 'floodlightActivityId': floodlight_activity_id, - 'floodlightConfigurationId': floodlight_config_id, - 'ordinal': ordinal, - 'timestampMicros': timestamp - } - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion['quantity'] = new_quantity - conversion['value'] = new_value - - # Construct the encryption info. - encryption_info = { - 'encryptionEntityId': encryption_entity_id, - 'encryptionEntityType': encryption_entity_type, - 'encryptionSource': encryption_source - } - - # Update the conversion. - request_body = { - 'conversions': [conversion], - 'encryptionInfo': encryption_info - } - request = service.conversions().batchupdate( - profileId=profile_id, body=request_body) - response = request.execute() - - if not response['hasFailures']: - print('Successfully updated conversion for encrypted user ID %s.' % - encrypted_user_id) - else: - print('Error(s) updating conversion for encrypted user ID %s.' % - encrypted_user_id) - - status = response['status'][0] - for error in status['errors']: - print '\t[%s]: %s' % (error['code'], error['message']) - - except client.AccessTokenRefreshError: - print('The credentials have been revoked or expired, please re-run the ' - 'application to re-authorize') - - -if __name__ == '__main__': - main(sys.argv) diff --git a/ruby/v3.4/Gemfile b/ruby/v3.4/Gemfile deleted file mode 100644 index 396dc2f..0000000 --- a/ruby/v3.4/Gemfile +++ /dev/null @@ -1,4 +0,0 @@ -source 'https://rubygems.org' - -gem 'google-api-client', '0.36.0' -gem 'googleauth', '>= 0.5', '< 0.10.0' diff --git a/ruby/v3.4/Gemfile.lock b/ruby/v3.4/Gemfile.lock deleted file mode 100644 index 6c1e487..0000000 --- a/ruby/v3.4/Gemfile.lock +++ /dev/null @@ -1,53 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - addressable (2.8.0) - public_suffix (>= 2.0.2, < 5.0) - declarative (0.0.10) - declarative-option (0.1.0) - faraday (0.17.1) - multipart-post (>= 1.2, < 3) - google-api-client (0.36.0) - addressable (~> 2.5, >= 2.5.1) - googleauth (~> 0.9) - httpclient (>= 2.8.1, < 3.0) - mini_mime (~> 1.0) - representable (~> 3.0) - retriable (>= 2.0, < 4.0) - signet (~> 0.12) - googleauth (0.9.0) - faraday (~> 0.12) - jwt (>= 1.4, < 3.0) - memoist (~> 0.16) - multi_json (~> 1.11) - os (>= 0.9, < 2.0) - signet (~> 0.7) - httpclient (2.8.3) - jwt (2.2.1) - memoist (0.16.2) - mini_mime (1.0.2) - multi_json (1.14.1) - multipart-post (2.1.1) - os (1.0.1) - public_suffix (4.0.6) - representable (3.0.4) - declarative (< 0.1.0) - declarative-option (< 0.2.0) - uber (< 0.2.0) - retriable (3.1.2) - signet (0.12.0) - addressable (~> 2.3) - faraday (~> 0.9) - jwt (>= 1.5, < 3.0) - multi_json (~> 1.10) - uber (0.1.0) - -PLATFORMS - ruby - -DEPENDENCIES - google-api-client (= 0.36.0) - googleauth (>= 0.5, < 0.10.0) - -BUNDLED WITH - 2.0.2 diff --git a/ruby/v3.4/README.md b/ruby/v3.4/README.md deleted file mode 100644 index 58b8c58..0000000 --- a/ruby/v3.4/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# DCM/DFA Reporting and Trafficking API Ruby Samples - -This is a collection of samples written in Ruby which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - -Please make sure that you're running Ruby 1.9+ and you've run -`bundle install` on the example directory to install all prerequisites. - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Running the Examples - -I'm assuming you've checked out the code and are reading this from a local -directory. If not check out the code to a local directory. - -1. Start up a sample, e.g. - - $ bundle exec ruby create_report.rb - -2. Complete the authorization steps on your browser - -3. Examine your shell output, be inspired and start hacking an amazing new app! diff --git a/ruby/v3.4/ads/create_rotation_group.rb b/ruby/v3.4/ads/create_rotation_group.rb deleted file mode 100755 index dda13a5..0000000 --- a/ruby/v3.4/ads/create_rotation_group.rb +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a rotation group ad in a given campaign. - -require_relative '../dfareporting_utils' - -def create_rotation_group(profile_id, campaign_id, placement_id, creative_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the campaign (to get end date). - campaign = service.get_campaign(profile_id, campaign_id) - - # Construct creative assignment. - creative_assignment = - DfareportingUtils::API_NAMESPACE::CreativeAssignment.new( - active: true, - creative_id: creative_id, - click_through_url: DfareportingUtils::API_NAMESPACE::ClickThroughUrl.new( - default_landing_page: true - ) - ) - - # Construct placement assignment. - placement_assignment = - DfareportingUtils::API_NAMESPACE::PlacementAssignment.new( - active: true, - placement_id: placement_id - ) - - # Construct creative rotation. - creative_rotation = DfareportingUtils::API_NAMESPACE::CreativeRotation.new( - creative_assignments: [creative_assignment], - type: 'CREATIVE_ROTATION_TYPE_RANDOM', - weight_calculation_strategy: 'WEIGHT_STRATEGY_OPTIMIZED' - ) - - # Construct delivery schedule. - delivery_schedule = DfareportingUtils::API_NAMESPACE::DeliverySchedule.new( - impression_ratio: 1, - priority: 'AD_PRIORITY_01' - ) - - # Construct and save ad. - ad = DfareportingUtils::API_NAMESPACE::Ad.new( - active: true, - campaign_id: campaign_id, - creative_rotation: creative_rotation, - delivery_schedule: delivery_schedule, - end_time: format('%sT00:00:00Z', campaign.end_date), - name: 'Example Rotation Group', - placement_assignments: [placement_assignment], - start_time: format('%sT23:59:59Z', Time.now.strftime('%Y-%m-%d')), - type: 'AD_SERVING_STANDARD_AD' - ) - - result = service.insert_ad(profile_id, ad) - - puts format('Created rotation group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :placement_id, :creative_id) - - create_rotation_group(args[:profile_id], args[:campaign_id], - args[:placement_id], args[:creative_id]) -end diff --git a/ruby/v3.4/ads/get_ads.rb b/ruby/v3.4/ads/get_ads.rb deleted file mode 100755 index 642d565..0000000 --- a/ruby/v3.4/ads/get_ads.rb +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all active ads your DCM user profile can see. -# -# Only name and ID are returned. - -require_relative '../dfareporting_utils' - -def get_ads(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_ads(profile_id, - page_token: token, - fields: 'nextPageToken,ads(id,name)') - - # Display results. - if result.ads.any? - result.ads.each do |ad| - puts format('Found ad with ID %d and name "%s".', ad.id, ad.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_ads(args[:profile_id]) -end diff --git a/ruby/v3.4/advertisers/assign_advertiser_to_advertiser_group.rb b/ruby/v3.4/advertisers/assign_advertiser_to_advertiser_group.rb deleted file mode 100755 index f6543c5..0000000 --- a/ruby/v3.4/advertisers/assign_advertiser_to_advertiser_group.rb +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example assigns an advertiser to an advertiser group. -# -# CAUTION: An advertiser that has campaigns associated with it cannot be -# removed from an advertiser group once assigned. - -require_relative '../dfareporting_utils' - -def assign_advertiser_to_advertiser_group(profile_id, advertiser_id, - advertiser_group_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a the advertiser group association to patch. - advertiser = DfareportingUtils::API_NAMESPACE::Advertiser.new( - advertiser_group_id: advertiser_group_id - ) - - # Patch the advertiser group association. - result = service.patch_advertiser(profile_id, advertiser_id, advertiser) - - # Display results - puts format('Assigned advertiser with ID %d to advertiser group with ID %d.', - result.id, result.advertiser_group_id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :advertiser_group_id) - - assign_advertiser_to_advertiser_group(args[:profile_id], - args[:advertiser_id], args[:advertiser_group_id]) -end diff --git a/ruby/v3.4/advertisers/create_advertiser.rb b/ruby/v3.4/advertisers/create_advertiser.rb deleted file mode 100755 index 0e1eb29..0000000 --- a/ruby/v3.4/advertisers/create_advertiser.rb +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an advertiser in a given DCM account. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_advertiser(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new advertiser resource to insert. - advertiser = DfareportingUtils::API_NAMESPACE::Advertiser.new( - name: format('Example Advertiser #%s', SecureRandom.hex(3)), - status: 'APPROVED' - ) - - # Insert the advertiser. - result = service.insert_advertiser(profile_id, advertiser) - - # Display results. - puts format('Created advertiser with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_advertiser(args[:profile_id]) -end diff --git a/ruby/v3.4/advertisers/create_advertiser_group.rb b/ruby/v3.4/advertisers/create_advertiser_group.rb deleted file mode 100755 index a74ea38..0000000 --- a/ruby/v3.4/advertisers/create_advertiser_group.rb +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an advertiser group. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_advertiser_group(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new advertiser group resource to insert. - advertiser_group = DfareportingUtils::API_NAMESPACE::AdvertiserGroup.new( - name: format('Example Advertiser Group #%s', SecureRandom.hex(3)) - ) - - # Insert the advertiser group. - result = service.insert_advertiser_group(profile_id, advertiser_group) - - # Display results. - puts format('Created advertiser group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_advertiser_group(args[:profile_id]) -end diff --git a/ruby/v3.4/advertisers/create_advertiser_landing_page.rb b/ruby/v3.4/advertisers/create_advertiser_landing_page.rb deleted file mode 100755 index 809eda5..0000000 --- a/ruby/v3.4/advertisers/create_advertiser_landing_page.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an advertiser landing page. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_advertiser_landing_page(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new landing page resource to insert. - landing_page = DfareportingUtils::API_NAMESPACE::LandingPage.new( - advertiser_id: advertiser_id, - archived: false, - name: format('Example Advertiser Landing Page #%s', SecureRandom.hex(3)), - url: 'https://www.google.com' - ) - - # Insert the advertiser landing page. - result = service.insert_advertiser_landing_page(profile_id, landing_page) - - # Display results. - puts format('Created advertiser landing page with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_advertiser_landing_page(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/advertisers/get_advertiser_groups.rb b/ruby/v3.4/advertisers/get_advertiser_groups.rb deleted file mode 100755 index a4fe958..0000000 --- a/ruby/v3.4/advertisers/get_advertiser_groups.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all advertiser groups for the specified user profile. - -require_relative '../dfareporting_utils' - -def get_advertiser_groups(profile_id) - # Authenticate and initialize API service - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_advertiser_groups(profile_id, - page_token: token, - fields: 'nextPageToken,advertiserGroups(id,name)') - - # Display results. - if result.advertiser_groups.any? - result.advertiser_groups.each do |group| - puts format('Found advertiser group with ID %d and name "%s".', - group.id, group.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_advertiser_groups(args[:profile_id]) -end diff --git a/ruby/v3.4/advertisers/get_advertiser_landing_pages.rb b/ruby/v3.4/advertisers/get_advertiser_landing_pages.rb deleted file mode 100755 index 2db2713..0000000 --- a/ruby/v3.4/advertisers/get_advertiser_landing_pages.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all advertiser landing pages for the specified user -# profile. - -require_relative '../dfareporting_utils' - -def get_advertiser_landing_pages(profile_id, advertiser_id) - # Authenticate and initialize API service - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_advertiser_landing_pages(profile_id, - advertiser_ids: [advertiser_id], - page_token: token, - fields: 'nextPageToken,landingPages(id,name)') - - # Display results. - if result.landing_pages.any? - result.landing_pages.each do |landing_page| - puts format('Found advertiser landing page with ID %d and name "%s".', - landing_page.id, landing_page.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_advertiser_landing_pages(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/advertisers/get_advertisers.rb b/ruby/v3.4/advertisers/get_advertisers.rb deleted file mode 100755 index 9f97fb8..0000000 --- a/ruby/v3.4/advertisers/get_advertisers.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all advertisers. - -require_relative '../dfareporting_utils' - -def get_advertisers(profile_id) - # Authenticate and initialize API service - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_advertisers(profile_id, - page_token: token, - fields: 'nextPageToken,advertisers(id,name)') - - # Display results. - if result.advertisers.any? - result.advertisers.each do |advertiser| - puts format('Found advertiser with ID %d and name "%s".', - advertiser.id, advertiser.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_advertisers(args[:profile_id]) -end diff --git a/ruby/v3.4/auth/authenticate_using_service_account.rb b/ruby/v3.4/auth/authenticate_using_service_account.rb deleted file mode 100755 index c5064af..0000000 --- a/ruby/v3.4/auth/authenticate_using_service_account.rb +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example demonstrates how to authenticate using a service account. -# -# An optional Google account email to impersonate may be specified as follows: -# authenticate_using_service_account.rb --i -# -# This optional flag only applies to service accounts which have domain-wide -# delegation enabled and wish to make API requests on behalf of an account -# within that domain. Using this flag will not allow you to impersonate a -# user from a domain you don't own (e.g., gmail.com). - -require 'google/apis/dfareporting_v3_4' -require 'googleauth' -require 'optparse' - -API_NAMESPACE = Google::Apis::DfareportingV3_4 - -def authenticate_using_service_account(path_to_json_file, impersonation_email) - # Create a Dfareporting service object. - # - # Note: application name should be replaced with a value that identifies - # your application. Suggested format is "MyCompany-ProductName". - service = API_NAMESPACE::DfareportingService.new - service.client_options.application_name = 'Ruby service account sample' - service.client_options.application_version = '1.0.0' - - # Generate an authorization object from the specified JSON file. - File.open(path_to_json_file, 'r+') do |json| - service.authorization = - Google::Auth::ServiceAccountCredentials.make_creds( - json_key_io: json, - scope: [API_NAMESPACE::AUTH_DFAREPORTING] - ) - end - - # Configure impersonation (if applicable). - service.authorization.sub = impersonation_email unless - impersonation_email.nil? - - service -end - -def get_userprofiles(service) - # Get all user profiles. - result = service.list_user_profiles - - # Display results. - result.items.each do |profile| - puts format( - 'User profile with ID %d and name "%s" was found for account %d.', - profile.profile_id, profile.user_name, profile.account_id - ) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - impersonation_email = nil - optparse = OptionParser.new do |opts| - opts.banner = format('Usage: %s path_to_json_file [options]', $PROGRAM_NAME) - opts.on_tail('-i', '--impersonate EMAIL', - 'Google account email to impersonate') do |email| - impersonation_email = email - end - end - optparse.parse! - - if ARGV.empty? - puts optparse - exit(-1) - end - - # Authenticate and initialize API service using service account. - service = authenticate_using_service_account(ARGV.shift, impersonation_email) - - get_userprofiles(service) -end diff --git a/ruby/v3.4/auth/authenticate_using_user_account.rb b/ruby/v3.4/auth/authenticate_using_user_account.rb deleted file mode 100755 index 827ad21..0000000 --- a/ruby/v3.4/auth/authenticate_using_user_account.rb +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example demonstrates how to authenticate using a user account, via the -# OAuth 2.0 installed application flow. - -require 'google/apis/dfareporting_v3_4' -require 'googleauth' -require 'googleauth/stores/file_token_store' - -API_NAMESPACE = Google::Apis::DfareportingV3_4 - -# This redirect URI allows you to copy the token from the success screen. -OAUTH_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze - -# Location where authorization credentials will be cached. -TOKEN_STORE_DIR = File.join(File.dirname(__FILE__), 'auth-sample.yaml') - -def authenticate_using_user_account(path_to_json_file, token_store) - # Load client ID from the specified file. - client_id = Google::Auth::ClientId.from_file(path_to_json_file) - - # Set up the user authorizer. - # - # Note: providing a token store allows auth credentials to be cached, so they - # survive multiple runs of the application. This avoids prompting the user for - # authorization every time the access token expires, by remembering the - # refresh token. - authorizer = Google::Auth::UserAuthorizer.new( - client_id, [API_NAMESPACE::AUTH_DFAREPORTING], token_store - ) - - # Authorize and persist credentials to the data store. - # - # Note: the 'user' value below is used to identify a specific set of - # credentials in the token store. You may provide different values here to - # persist credentials for multiple users to the same token store. - authorization = authorizer.get_credentials('user') - if authorization.nil? - puts format( - "Open this URL in your browser and authorize the application.\n\n%s" \ - "\n\nEnter the authorization code:", - authorizer.get_authorization_url(base_url: OAUTH_REDIRECT_URI) - ) - code = STDIN.gets.chomp - authorization = authorizer.get_and_store_credentials_from_code( - base_url: OAUTH_REDIRECT_URI, code: code, user_id: 'user' - ) - end - - authorization -end - -def create_dfareporting_service_instance(authorization) - # Create a Dfareporting service object. - # - # Note: application name should be replaced with a value that identifies - # your application. Suggested format is "MyCompany-ProductName". - service = API_NAMESPACE::DfareportingService.new - service.authorization = authorization - service.client_options.application_name = 'Ruby installed app sample' - service.client_options.application_version = '1.0.0' - - service -end - -def get_userprofiles(service) - # Get all user profiles. - result = service.list_user_profiles - - # Display results. - result.items.each do |profile| - puts format( - 'User profile with ID %d and name "%s" was found for account %d.', - profile.profile_id, profile.user_name, profile.account_id - ) - end -end - -if $PROGRAM_NAME == __FILE__ - if ARGV.empty? - puts format('Usage: %s path_to_json_file', $PROGRAM_NAME) - exit(-1) - end - - # Authenticate using user account. - authorization = authenticate_using_user_account( - ARGV.shift, - Google::Auth::Stores::FileTokenStore.new(file: TOKEN_STORE_DIR) - ) - - # Initialize API service, - service = create_dfareporting_service_instance(authorization) - - get_userprofiles(service) -end diff --git a/ruby/v3.4/campaigns/create_campaign.rb b/ruby/v3.4/campaigns/create_campaign.rb deleted file mode 100755 index 4feceb4..0000000 --- a/ruby/v3.4/campaigns/create_campaign.rb +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a campaign in a given advertiser. -# -# To create an advertiser, run create_advertiser.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_campaign(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Create a new campaign resource to insert. - campaign = DfareportingUtils::API_NAMESPACE::Campaign.new( - advertiser_id: advertiser_id, - archived: false, - default_landing_page_id: default_landing_page.id, - name: format('Example Campaign #%s', SecureRandom.hex(3)), - start_date: '2014-01-01', - end_date: '2020-01-01' - ) - - # Insert the campaign. - result = service.insert_campaign(profile_id, campaign) - - # Display results. - puts format('Created campaign with ID %d and name "%s".', result.id, - result.name) -end - -def get_advertiser_landing_page(service, profile_id, advertiser_id) - # Retrieve a sigle landing page from the specified advertiser. - result = service.list_advertiser_landing_pages(profile_id, - advertiser_ids: [advertiser_id], - max_results: 1) - - if result.landing_pages.none? - abort format('No landing pages for for advertiser with ID %d', - advertiser_id) - end - - result.landing_pages[0] -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_campaign(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/campaigns/create_campaign_event_tag.rb b/ruby/v3.4/campaigns/create_campaign_event_tag.rb deleted file mode 100755 index 18d221e..0000000 --- a/ruby/v3.4/campaigns/create_campaign_event_tag.rb +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative field associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_campaign_event_tag(profile_id, campaign_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new event tag resource to insert. - event_tag = DfareportingUtils::API_NAMESPACE::EventTag.new( - campaign_id: campaign_id, - name: format('Example Campaign Event Tag #%s', SecureRandom.hex(3)), - status: 'ENABLED', - type: 'CLICK_THROUGH_EVENT_TAG', - url: 'https://www.google.com' - ) - - # Insert the event tag. - result = service.insert_event_tag(profile_id, event_tag) - - # Display results. - puts format('Created campaign event tag with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id) - - create_campaign_event_tag(args[:profile_id], args[:campaign_id]) -end diff --git a/ruby/v3.4/campaigns/get_campaigns.rb b/ruby/v3.4/campaigns/get_campaigns.rb deleted file mode 100755 index 81fa930..0000000 --- a/ruby/v3.4/campaigns/get_campaigns.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all existing campaigns for the specified user profile. - -require_relative '../dfareporting_utils' - -def get_campaigns(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_campaigns(profile_id, - page_token: token, - fields: 'nextPageToken,campaigns(id,name)') - - # Display results. - if result.campaigns.any? - result.campaigns.each do |campaign| - puts format('Found campaign with ID %d and name "%s".', campaign.id, - campaign.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_campaigns(args[:profile_id]) -end diff --git a/ruby/v3.4/client_secrets.json b/ruby/v3.4/client_secrets.json deleted file mode 100644 index f9cf7ff..0000000 --- a/ruby/v3.4/client_secrets.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "installed": { - "client_id": "[[INSERT CLIENT ID HERE]]", - "client_secret": "[[INSERT CLIENT SECRET HERE]]", - "redirect_uris": [], - "auth_uri": "https://accounts.google.com/o/oauth2/auth", - "token_uri": "https://accounts.google.com/o/oauth2/token" - } -} \ No newline at end of file diff --git a/ruby/v3.4/conversions/insert_offline_mobile_conversion.rb b/ruby/v3.4/conversions/insert_offline_mobile_conversion.rb deleted file mode 100755 index 5cbafdb..0000000 --- a/ruby/v3.4/conversions/insert_offline_mobile_conversion.rb +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example inserts an offline conversion attributed to a mobile device ID. - -require_relative '../dfareporting_utils' -require 'date' - -def insert_offline_mobile_conversion(profile_id, mobile_device_id, - floodlight_activity_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - floodlight_activity_id) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - current_time_in_micros = DateTime.now.strftime('%Q').to_i * 1000 - - # Construct the conversion. - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - floodlight_activity_id: floodlight_activity_id, - floodlight_configuration_id: floodlight_config_id, - ordinal: current_time_in_micros, - mobile_device_id: mobile_device_id, - timestamp_micros: current_time_in_micros - ) - - # Construct the batch insert request. - batch_insert_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchInsertRequest.new( - conversions: [conversion] - ) - - # Insert the conversion. - result = service.batchinsert_conversion(profile_id, batch_insert_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) inserting conversion for mobile device ID %s.', - mobile_device_id) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully inserted conversion for mobile device ID %s.', - mobile_device_id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :mobile_device_id, - :floodlight_activity_id) - - insert_offline_mobile_conversion(args[:profile_id], args[:mobile_device_id], - args[:floodlight_activity_id]) -end diff --git a/ruby/v3.4/conversions/insert_offline_user_conversion.rb b/ruby/v3.4/conversions/insert_offline_user_conversion.rb deleted file mode 100755 index 7f03ea9..0000000 --- a/ruby/v3.4/conversions/insert_offline_user_conversion.rb +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example inserts an offline conversion attributed to an encrypted user -# ID. - -require_relative '../dfareporting_utils' -require 'date' - -# Inserts an offline user conversions with the specified values. -# -# @param profile_id [Number] The ID of the DCM user issuing this request. -# @param encrypted_user_id [String] The encrypted user ID to which the -# conversion should be attributed. -# @param floodlight_activity_id [Number] The Floodlight activity ID to which -# the conversion should be attributed. -# @param encryption [Object] A hash containing the values used to encrypt the -# specified user ID. The expected format is: -# { -# source: , -# entity_id: , -# entity_type: -# } -def insert_offline_user_conversion(profile_id, encrypted_user_id, - floodlight_activity_id, encryption = {}) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - floodlight_activity_id) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - current_time_in_micros = DateTime.now.strftime('%Q').to_i * 1000 - - # Construct the conversion. - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - encrypted_user_id: encrypted_user_id, - floodlight_activity_id: floodlight_activity_id, - floodlight_configuration_id: floodlight_config_id, - ordinal: current_time_in_micros, - timestamp_micros: current_time_in_micros - ) - - # Construct the encryption info. - encryption_info = DfareportingUtils::API_NAMESPACE::EncryptionInfo.new( - encryption_entity_id: encryption[:entity_id], - encryption_entity_type: encryption[:entity_type], - encryption_source: encryption[:source] - ) - - # Construct the batch insert request. - batch_insert_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchInsertRequest.new( - conversions: [conversion], - encryption_info: encryption_info - ) - - # Insert the conversion. - result = service.batchinsert_conversion(profile_id, batch_insert_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) inserting conversion for encrypted user ID %s.', - encrypted_user_id) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully inserted conversion for encrypted user ID %s.', - encrypted_user_id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :encrypted_user_id, :encryption_source, :encryption_entity_id, - :encryption_entity_type, :floodlight_activity_id) - - insert_offline_user_conversion(args[:profile_id], args[:encrypted_user_id], - args[:floodlight_activity_id], - source: args[:encryption_source], - entity_id: args[:encryption_entity_id], - entity_type: args[:encryption_entity_type]) -end diff --git a/ruby/v3.4/conversions/update_offline_mobile_conversion.rb b/ruby/v3.4/conversions/update_offline_mobile_conversion.rb deleted file mode 100755 index 6e1cb75..0000000 --- a/ruby/v3.4/conversions/update_offline_mobile_conversion.rb +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example updates an offline conversion attributed to a mobile device ID. -# -# To create a conversion attributed to a mobile device ID, run -# insert_offline_mobile_conversion.rb. - -require_relative '../dfareporting_utils' - -# Updates an offline mobile conversion with the specified values. -# -# @param profile_id [Number] The ID of the DCM user issuing this request. -# @param new_quantity [Number] The new quantity value to assign to the -# specified conversion. -# @param new_value [Number] The new value to assign to the specified -# conversion. -# @param existing_conversion [Object] A hash containing values that identify -# an existing offline mobile conversion. The expected format is: -# { -# mobile_device_id: , -# floodlight_activity_id: , -# ordinal: , -# timestamp: -# } -def update_offline_mobile_conversion(profile_id, new_quantity, new_value, - existing_conversion = {}) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - existing_conversion[:floodlight_activity_id]) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - # Construct the conversion with values that identify the conversion to - # update - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - floodlight_activity_id: existing_conversion[:floodlight_activity_id], - floodlight_configuration_id: floodlight_config_id, - ordinal: existing_conversion[:ordinal], - mobile_device_id: existing_conversion[:mobile_device_id], - timestamp_micros: existing_conversion[:timestamp] - ) - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion.quantity = new_quantity - conversion.value = new_value - - # Construct the batch update request. - batch_update_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchUpdateRequest.new( - conversions: [conversion] - ) - - # Update the conversion. - result = service.batchupdate_conversion(profile_id, batch_update_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) updating conversion for mobile device ID %s.', - existing_conversion[:mobile_device_id]) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully updated conversion for mobile device ID %s.', - existing_conversion[:mobile_device_id]) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :mobile_device_id, - :floodlight_activity_id, :ordinal, :timestamp, :new_quantity, :new_value) - - update_offline_mobile_conversion( - args[:profile_id], args[:new_quantity], args[:new_value], - mobile_device_id: args[:mobile_device_id], - floodlight_activity_id: args[:floodlight_activity_id], - ordinal: args[:ordinal], - timestamp: args[:timestamp] - ) -end diff --git a/ruby/v3.4/conversions/update_offline_user_conversion.rb b/ruby/v3.4/conversions/update_offline_user_conversion.rb deleted file mode 100755 index c851938..0000000 --- a/ruby/v3.4/conversions/update_offline_user_conversion.rb +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example updates an offline conversion attributed to an encrypted user -# ID. -# -# To create a conversion attributed to an encrypted user ID, run -# insert_offline_user_conversion.rb. - -require_relative '../dfareporting_utils' - -# Updates an offline user conversion with the specified values. -# -# @param profile_id [Number] The ID of the DCM user issuing this request. -# @param new_quantity [Number] The new quantity value to assign to the -# specified conversion. -# @param new_value [Number] The new value to assign to the specified -# conversion. -# @param existing_conversion [Object] A hash containing values that identify -# an existing offline user conversion. The expected format is: -# { -# encrypted_user_id: , -# floodlight_activity_id: , -# ordinal: , -# timestamp: -# } -# @param encryption [Object] A hash containing the values used to encrypt the -# existing user conversion. The expected format is: -# { -# source: , -# entity_id: , -# entity_type: -# } -def update_offline_user_conversion(profile_id, new_quantity, new_value, - existing_conversion = {}, encryption = {}) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - existing_conversion[:floodlight_activity_id]) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - # Construct the conversion with values that identify the conversion to - # update. - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - encrypted_user_id: existing_conversion[:encrypted_user_id], - floodlight_activity_id: existing_conversion[:floodlight_activity_id], - floodlight_configuration_id: floodlight_config_id, - ordinal: existing_conversion[:ordinal], - timestamp_micros: existing_conversion[:timestamp] - ) - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion.quantity = new_quantity - conversion.value = new_value - - # Construct the encryption info. - encryption_info = DfareportingUtils::API_NAMESPACE::EncryptionInfo.new( - encryption_entity_id: encryption[:entity_id], - encryption_entity_type: encryption[:entity_type], - encryption_source: encryption[:source] - ) - - # Construct the batch update request. - batch_update_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchUpdateRequest.new( - conversions: [conversion], - encryption_info: encryption_info - ) - - # Update the conversion. - result = service.batchupdate_conversion(profile_id, batch_update_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) updating conversion for encrypted user ID %s.', - existing_conversion[:encrypted_user_id]) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully updated conversion for encrypted user ID %s.', - existing_conversion[:encrypted_user_id]) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :encrypted_user_id, :encryption_source, :encryption_entity_id, - :encryption_entity_type, :floodlight_activity_id, :ordinal, :timestamp, - :new_quantity, :new_value) - - update_offline_user_conversion( - args[:profile_id], args[:new_quantity], args[:new_value], - { - encrypted_user_id: args[:encrypted_user_id], - floodlight_activity_id: args[:floodlight_activity_id], - ordinal: args[:ordinal], - timestamp: args[:timestamp] - }, - source: args[:encryption_source], - entity_id: args[:encryption_entity_id], - entity_type: args[:encryption_entity_type] - ) -end diff --git a/ruby/v3.4/creative_asset_utils.rb b/ruby/v3.4/creative_asset_utils.rb deleted file mode 100755 index d4d112a..0000000 --- a/ruby/v3.4/creative_asset_utils.rb +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Utility class for handling common tasks related to working with creative -# assets. - -require_relative 'dfareporting_utils' - -# Creative asset utilities used by DFA Reporting and Trafficking API creative -# examples. -class CreativeAssetUtils - # Creates a new instance of CreativeAssetUtils. - def initialize(service, profile_id) - @service = service - @profile_id = profile_id - end - - # Uploads a creative asset and returns the creative asset metadata. - def upload_asset(advertiser_id, path_to_asset_file, asset_type) - asset_name = File.basename(path_to_asset_file) - - # Construct the creative asset metadata - creative_asset = DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: DfareportingUtils::API_NAMESPACE::CreativeAssetId.new( - name: asset_name, - type: asset_type - ) - ) - - # Upload the asset. - mime_type = determine_mime_type(path_to_asset_file, asset_type) - - result = @service.insert_creative_asset( - @profile_id, - advertiser_id, - creative_asset, - content_type: mime_type, - upload_source: path_to_asset_file - ) - - puts format('Creative asset was saved with name "%s".', - result.asset_identifier.name) - - result - end - - # Performs a naive mime-type lookup based on file name and asset type. - def determine_mime_type(path_to_asset_file, asset_type) - case asset_type - when 'IMAGE', 'HTML_IMAGE' - return format('image/%s', File.extname(path_to_asset_file)) - when 'VIDEO' - format('video/%s', File.extname(path_to_asset_file)) - else - 'application/octet-stream' - end - end -end diff --git a/ruby/v3.4/creatives/assign_creative_to_campaign.rb b/ruby/v3.4/creatives/assign_creative_to_campaign.rb deleted file mode 100755 index 142ad79..0000000 --- a/ruby/v3.4/creatives/assign_creative_to_campaign.rb +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example assigns a given creative to a given campaign. -# -# Note that both the creative and campaign must be associated with the same -# advertiser. - -require_relative '../dfareporting_utils' - -def assign_creative_to_campaign(profile_id, campaign_id, creative_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative-campaign association to insert - association = - DfareportingUtils::API_NAMESPACE::CampaignCreativeAssociation.new( - creative_id: creative_id - ) - - # Insert the advertiser group. - result = service.insert_campaign_creative_association(profile_id, campaign_id, - association) - - # Display results. - puts format('Creative with ID %d is now associated with campaign %d.', - result.creative_id, campaign_id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :creative_id) - - assign_creative_to_campaign(args[:profile_id], args[:campaign_id], - args[:creative_id]) -end diff --git a/ruby/v3.4/creatives/create_creative_field.rb b/ruby/v3.4/creatives/create_creative_field.rb deleted file mode 100755 index dd1e7d9..0000000 --- a/ruby/v3.4/creatives/create_creative_field.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative field associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_creative_field(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative field resource to insert, - creative_field = DfareportingUtils::API_NAMESPACE::CreativeField.new( - advertiser_id: advertiser_id, - name: format('Example Creative Field #%s', SecureRandom.hex(3)) - ) - - # Insert the creative field, - result = service.insert_creative_field(profile_id, creative_field) - - # Display results, - puts format('Created creative field with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments, - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_creative_field(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/creatives/create_creative_field_value.rb b/ruby/v3.4/creatives/create_creative_field_value.rb deleted file mode 100755 index 8daf06a..0000000 --- a/ruby/v3.4/creatives/create_creative_field_value.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative field value for a given creative field. -# -# To get the creative field ID, run get_creative_fields.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_creative_field_value(profile_id, field_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative field value resource to insert. - field_value = DfareportingUtils::API_NAMESPACE::CreativeFieldValue.new( - value: format('Example Creative Field Value #%s', SecureRandom.hex(3)) - ) - - # Insert the creative field value. - result = service.insert_creative_field_value(profile_id, field_id, - field_value) - - # Display results. - puts format('Created creative field value with ID %d and value "%s".', - result.id, result.value) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :field_id) - - create_creative_field_value(args[:profile_id], args[:field_id]) -end diff --git a/ruby/v3.4/creatives/create_creative_group.rb b/ruby/v3.4/creatives/create_creative_group.rb deleted file mode 100755 index 41f3054..0000000 --- a/ruby/v3.4/creatives/create_creative_group.rb +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative group associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. Valid group numbers are -# limited to 1 or 2. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_creative_group(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative group resource to insert. - creative_group = DfareportingUtils::API_NAMESPACE::CreativeGroup.new( - advertiser_id: advertiser_id, - group_number: 1, - name: format('Example Creative Group #%s', SecureRandom.hex(3)) - ) - - # Insert the creative group. - result = service.insert_creative_group(profile_id, creative_group) - - # Display results. - puts format('Created creative group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_creative_group(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/creatives/create_display_image_gallery_creative.rb b/ruby/v3.4/creatives/create_display_image_gallery_creative.rb deleted file mode 100755 index 720d37f..0000000 --- a/ruby/v3.4/creatives/create_display_image_gallery_creative.rb +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a display image gallery creative. -# -# Requires two image assets and an advertiser ID as input. To get an advertiser -# ID, run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_enhanced_image_creative(profile_id, advertiser_id, size_id, - path_to_image1_file, path_to_image2_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - util = CreativeAssetUtils.new(service, profile_id) - - # Upload the first image asset. - image1_asset_id = util.upload_asset(advertiser_id, path_to_image1_file, - 'HTML_IMAGE').asset_identifier - - # Upload the second image asset. - image2_asset_id = util.upload_asset(advertiser_id, path_to_image2_file, - 'HTML_IMAGE').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - auto_advance_images: true, - click_tags: [ - DfareportingUtils::API_NAMESPACE::ClickTag.new( - event_name: image1_asset_id.name, - name: image1_asset_id.name - ), - DfareportingUtils::API_NAMESPACE::ClickTag.new( - event_name: image2_asset_id.name, - name: image2_asset_id.name - ) - ], - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: image1_asset_id, - role: 'PRIMARY' - ), - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: image2_asset_id, - role: 'PRIMARY' - ) - ], - name: 'Example display image gallery creative', - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY_IMAGE_GALLERY' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format( - 'Created display image gallery creative with ID %d and name "%s".', - result.id, result.name - ) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :size_id, :path_to_image1_file, :path_to_image2_file) - - create_enhanced_image_creative(args[:profile_id], args[:advertiser_id], - args[:size_id], args[:path_to_image1_file], args[:path_to_image2_file]) -end diff --git a/ruby/v3.4/creatives/create_display_redirect_creative.rb b/ruby/v3.4/creatives/create_display_redirect_creative.rb deleted file mode 100755 index 68ed09d..0000000 --- a/ruby/v3.4/creatives/create_display_redirect_creative.rb +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a display redirect creative associated with a given -# advertiser. -# -# To get a size ID, run get_size.rb. - -require_relative '../dfareporting_utils' - -def create_tracking_creative(profile_id, advertiser_id, image_url, size_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative resource to insert. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - name: 'Example display redirect creative', - redirect_url: image_url, - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY_REDIRECT' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - # Display results. - puts format('Created display redirect creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :image_url, :size_id) - - create_tracking_creative(args[:profile_id], args[:advertiser_id], - args[:image_url], args[:size_id]) -end diff --git a/ruby/v3.4/creatives/create_html5_display_creative.rb b/ruby/v3.4/creatives/create_html5_display_creative.rb deleted file mode 100755 index 62abc6c..0000000 --- a/ruby/v3.4/creatives/create_html5_display_creative.rb +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an HTML5 display creative. -# -# Requires an HTML5 asset, backup image asset, and an advertiser ID as input. -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_html5_banner_creative(profile_id, advertiser_id, size_id, - path_to_html5_asset_file, path_to_backup_image_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - util = CreativeAssetUtils.new(service, profile_id) - - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Upload the HTML5 asset. - html5_asset_id = util.upload_asset(advertiser_id, path_to_html5_asset_file, - 'HTML').asset_identifier - - # Upload the backup image asset. - backup_image_asset_id = util.upload_asset(advertiser_id, - path_to_backup_image_file, 'HTML_IMAGE').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - backup_image_click_through_url: - DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new( - landing_page_id: default_landing_page.id - ), - backup_image_reporting_label: 'backup', - backup_image_target_window: - DfareportingUtils::API_NAMESPACE::TargetWindow.new( - target_window_option: 'NEW_WINDOW' - ), - click_tags: [ - DfareportingUtils::API_NAMESPACE::ClickTag.new( - event_name: 'exit', - name: 'click_tag', - click_through_url: - DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new( - landing_page_id: default_landing_page.id - ) - ) - ], - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: html5_asset_id, - role: 'PRIMARY' - ), - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: backup_image_asset_id, - role: 'BACKUP_IMAGE' - ) - ], - name: 'Example HTML5 display creative', - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created HTML5 display creative with ID %d and name "%s".', - result.id, result.name) -end - -def get_advertiser_landing_page(service, profile_id, advertiser_id) - # Retrieve a sigle landing page from the specified advertiser. - result = service.list_advertiser_landing_pages(profile_id, - advertiser_ids: [advertiser_id], - max_results: 1) - - if result.landing_pages.none? - abort format('No landing pages for for advertiser with ID %d', - advertiser_id) - end - - result.landing_pages[0] -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :size_id, :path_to_html5_asset_file, :path_to_backup_image_file) - - create_html5_banner_creative(args[:profile_id], args[:advertiser_id], - args[:size_id], args[:path_to_html5_asset_file], - args[:path_to_backup_image_file]) -end diff --git a/ruby/v3.4/creatives/create_image_display_creative.rb b/ruby/v3.4/creatives/create_image_display_creative.rb deleted file mode 100755 index df81b14..0000000 --- a/ruby/v3.4/creatives/create_image_display_creative.rb +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an image display creative. -# -# Requires an image asset and advertiser ID as input. To get an advertiser ID, -# run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_image_display_creative(profile_id, advertiser_id, size_id, - path_to_image_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Upload the creative asset. - util = CreativeAssetUtils.new(service, profile_id) - creative_asset_id = util.upload_asset(advertiser_id, path_to_image_file, - 'HTML_IMAGE').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: creative_asset_id, - role: 'PRIMARY' - ) - ], - name: 'Example image display creative', - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created image display creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :size_id, :path_to_image_file) - - create_image_display_creative(args[:profile_id], args[:advertiser_id], - args[:size_id], args[:path_to_image_file]) -end diff --git a/ruby/v3.4/creatives/create_instream_audio_creative.rb b/ruby/v3.4/creatives/create_instream_audio_creative.rb deleted file mode 100755 index ac2234d..0000000 --- a/ruby/v3.4/creatives/create_instream_audio_creative.rb +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2018, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an in-stream audio creative. -# -# Requires an audio asset and advertiser ID as input. To get an advertiser ID, -# run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_instream_audio_creative(profile_id, advertiser_id, - path_to_audio_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Upload the creative asset. - util = CreativeAssetUtils.new(service, profile_id) - creative_asset_id = util.upload_asset(advertiser_id, path_to_audio_file, - 'AUDIO').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: creative_asset_id, - role: 'PARENT_AUDIO' - ) - ], - name: 'Example in-stream audio creative', - type: 'INSTREAM_AUDIO' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created in-stream audio creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :path_to_audio_file) - - create_instream_audio_creative(args[:profile_id], args[:advertiser_id], - args[:path_to_audio_file]) -end diff --git a/ruby/v3.4/creatives/create_instream_video_creative.rb b/ruby/v3.4/creatives/create_instream_video_creative.rb deleted file mode 100755 index 027d15c..0000000 --- a/ruby/v3.4/creatives/create_instream_video_creative.rb +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an in-stream video creative. -# -# Requires a video asset and advertiser ID as input. To get an advertiser ID, -# run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_instream_video_creative(profile_id, advertiser_id, - path_to_video_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Upload the creative asset. - util = CreativeAssetUtils.new(service, profile_id) - creative_asset_id = util.upload_asset(advertiser_id, path_to_video_file, - 'VIDEO').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: creative_asset_id, - role: 'PARENT_VIDEO' - ) - ], - name: 'Example in-stream video creative', - type: 'INSTREAM_VIDEO' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created in-stream video creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :path_to_video_file) - - create_instream_video_creative(args[:profile_id], args[:advertiser_id], - args[:path_to_video_file]) -end diff --git a/ruby/v3.4/creatives/create_tracking_creative.rb b/ruby/v3.4/creatives/create_tracking_creative.rb deleted file mode 100755 index 302cb94..0000000 --- a/ruby/v3.4/creatives/create_tracking_creative.rb +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a tracking creative associated with a given advertiser. - -require_relative '../dfareporting_utils' - -def create_tracking_creative(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative resource to insert. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - name: 'Example Tracking Creative', - type: 'TRACKING_TEXT' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - # Display results. - puts format('Created tracking creative with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_tracking_creative(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/creatives/get_creative_field_values.rb b/ruby/v3.4/creatives/get_creative_field_values.rb deleted file mode 100755 index 8703fbb..0000000 --- a/ruby/v3.4/creatives/get_creative_field_values.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all creative field values. - -require_relative '../dfareporting_utils' - -def get_creative_field_values(profile_id, field_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creative_field_values(profile_id, field_id, - page_token: token, - fields: 'nextPageToken,creativeFieldValues(id,value)') - - # Display results. - if result.creative_field_values.any? - result.creative_field_values.each do |value| - puts format('Found creative field value with ID %d and value "%s".', - value.id, value.value) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :field_id) - - get_creative_field_values(args[:profile_id], args[:field_id]) -end diff --git a/ruby/v3.4/creatives/get_creative_fields.rb b/ruby/v3.4/creatives/get_creative_fields.rb deleted file mode 100755 index 04028cd..0000000 --- a/ruby/v3.4/creatives/get_creative_fields.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all creative fields. - -require_relative '../dfareporting_utils' - -def get_creative_fields(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creative_fields(profile_id, - page_token: token, - fields: 'nextPageToken,creativeFields(id,name)') - - # Display results. - if result.creative_fields.any? - result.creative_fields.each do |field| - puts format('Found creative field with ID %d and name "%s".', field.id, - field.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_creative_fields(args[:profile_id]) -end diff --git a/ruby/v3.4/creatives/get_creative_groups.rb b/ruby/v3.4/creatives/get_creative_groups.rb deleted file mode 100755 index 518f8c5..0000000 --- a/ruby/v3.4/creatives/get_creative_groups.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all creative groups. - -require_relative '../dfareporting_utils' - -def get_creative_groups(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creative_groups(profile_id, - page_token: token, - fields: 'nextPageToken,creativeGroups(id,name)') - - # Display results. - if result.creative_groups.any? - result.creative_groups.each do |group| - puts format('Found creative group with ID %d and name "%s".', group.id, - group.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_creative_groups(args[:profile_id]) -end diff --git a/ruby/v3.4/creatives/get_creatives.rb b/ruby/v3.4/creatives/get_creatives.rb deleted file mode 100755 index 1350a7f..0000000 --- a/ruby/v3.4/creatives/get_creatives.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all existing active creatives for a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' - -def get_creatives(profile_id, _advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creatives(profile_id, - page_token: token, - fields: 'nextPageToken,creatives(id,name,type)') - - # Display results. - if result.creatives.any? - result.creatives.each do |creative| - puts format('Found %s creative with ID %d and name "%s".', - creative.type, creative.id, creative.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_creatives(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/dfareporting_utils.rb b/ruby/v3.4/dfareporting_utils.rb deleted file mode 100755 index 017dd02..0000000 --- a/ruby/v3.4/dfareporting_utils.rb +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Handles common tasks across all DFA Reporting API samples. - -require 'google/apis/dfareporting_v3_4' -require 'googleauth' -require 'googleauth/stores/file_token_store' - -# Utility methods used by all DFA Reporting and Trafficking API samples. -module DfareportingUtils - API_NAME = 'dfareporting'.freeze - API_NAMESPACE = Google::Apis::DfareportingV3_4 - API_SCOPES = [ - API_NAMESPACE::AUTH_DDMCONVERSIONS, - API_NAMESPACE::AUTH_DFAREPORTING, - API_NAMESPACE::AUTH_DFATRAFFICKING - ].freeze - - CLIENT_SECRETS_FILE = 'client_secrets.json'.freeze - CREDENTIAL_STORE_FILE = "#{API_NAME}-oauth2.yaml".freeze - CREDENTIAL_STORE_PATH = File.dirname(__FILE__) - - # This redirect URI allows you to copy the token from the success screen. - OAUTH_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze - - # Handles validating command line arguments and returning them as a Hash - def self.parse_arguments(argument_values, *argument_names) - validate_arguments(argument_values, *argument_names) - generate_argument_map(argument_values, *argument_names) - end - - # Validates the number of command line arguments matches what was expected - def self.validate_arguments(argument_values, *argument_names) - return if argument_values.length == argument_names.length - - # Format the arguments for display (ie, '') - formatted_arguments = argument_names.map { |a| '<' + a.to_s + '>' } - - # Display a message to the user and exit - puts format('Usage: %s %s', $PROGRAM_NAME, formatted_arguments.join(' ')) - exit - end - private_class_method :validate_arguments - - # Converts parallel arrays of argument names and values into a single map - def self.generate_argument_map(argument_values, *argument_names) - ret = {} - argument_names.each_with_index do |arg, index| - ret[arg] = argument_values[index] - end - ret - end - private_class_method :generate_argument_map - - # Handles authentication and loading of the API. - def self.initialize_service - # Uncomment the following lines to enable logging. - # log_file = File.open("#{$0}.log", 'a+') - # log_file.sync = true - # logger = Logger.new(log_file) - # logger.level = Logger::DEBUG - # Google::Apis.logger = logger # Logging is set globally - - # Create an API Service object. - service = create_service_object - - # Load application default credentials if they're available. - authorization = authorize_application_default_credentials - - # Otherwise, load credentials from the provided client secrets file. - authorization = authorize_installed_application if authorization.nil? - - # If no credentials could be loaded, return an error. - if authorization.nil? - puts 'Could not load credentials. Enter client ID and secret from ' \ - 'https://console.developers.google.com/ into client_secrets.json.' - exit - end - - service.authorization = authorization - service - end - - # Returns an instance of the Dfareporting service without authentication. - def self.create_service_object - service = API_NAMESPACE::DfareportingService.new - service.client_options.application_name = "Ruby #{API_NAME} samples" - service.client_options.application_version = '1.0.0' - - service - end - private_class_method :create_service_object - - # Attempts to load application default credentials and return an - # authorization object that can be used to make requests. - def self.authorize_application_default_credentials - Google::Auth.get_application_default(API_SCOPES) - rescue StandardError - # No application default credentials, continue to try other options. - nil - end - private_class_method :authorize_application_default_credentials - - # Handles authorizing a user via the OAuth installed application flow and - # returns an authorization object that can be used to make requests. - def self.authorize_installed_application - # Load the client secrets. - client_id = load_client_secrets - return nil if client_id.nil? - - # FileTokenStore stores auth credentials in a file, so they survive - # multiple runs of the application. This avoids prompting the user for - # authorization every time the access token expires, by remembering the - # refresh token. - # - # Note: FileTokenStore is not suitable for multi-user applications. - token_store = Google::Auth::Stores::FileTokenStore.new( - file: File.join(CREDENTIAL_STORE_PATH, CREDENTIAL_STORE_FILE) - ) - - authorizer = Google::Auth::UserAuthorizer.new(client_id, API_SCOPES, - token_store) - - authorization = authorizer.get_credentials('default') - if authorization.nil? - puts format( - "Open this URL in your browser and authorize the application.\n\n%s" \ - "\n\nEnter the authorization code:", - authorizer.get_authorization_url(base_url: OAUTH_REDIRECT_URI) - ) - code = STDIN.gets.chomp - authorization = authorizer.get_and_store_credentials_from_code( - base_url: OAUTH_REDIRECT_URI, code: code, user_id: 'default' - ) - end - - authorization - end - private_class_method :authorize_installed_application - - def self.load_client_secrets - # Load client ID from the specified file. - client_id = Google::Auth::ClientId.from_file( - File.join(CREDENTIAL_STORE_PATH, CLIENT_SECRETS_FILE) - ) - - if client_id.id.start_with?('[[INSERT') || - client_id.secret.start_with?('[[INSERT') - return nil - end - - client_id - rescue StandardError - # Unable to load client_secrets.json. - nil - end - private_class_method :load_client_secrets -end diff --git a/ruby/v3.4/floodlight/create_floodlight_activity.rb b/ruby/v3.4/floodlight/create_floodlight_activity.rb deleted file mode 100755 index 3c200b3..0000000 --- a/ruby/v3.4/floodlight/create_floodlight_activity.rb +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a floodlight activity in a given activity group. -# -# To create an activity group, run create_floodlight_activity_group.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_floodlight_activity(profile_id, activity_group_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new floodlight activity resource to insert. - activity = DfareportingUtils::API_NAMESPACE::FloodlightActivity.new( - counting_method: 'STANDARD_COUNTING', - expected_url: 'http://www.google.com', - floodlight_activity_group_id: activity_group_id, - floodlight_tag_type: 'GLOBAL_SITE_TAG', - name: format('Example Floodlight Activity #%s', SecureRandom.hex(3)) - ) - - # Insert the floodlight activity. - result = service.insert_floodlight_activity(profile_id, activity) - - # Display results. - puts format('Created floodlight activity with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :activity_group_id) - - create_floodlight_activity(args[:profile_id], args[:activity_group_id]) -end diff --git a/ruby/v3.4/floodlight/create_floodlight_activity_group.rb b/ruby/v3.4/floodlight/create_floodlight_activity_group.rb deleted file mode 100755 index 33d1c81..0000000 --- a/ruby/v3.4/floodlight/create_floodlight_activity_group.rb +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a new activity group for a floodlight configuration. -# -# To get a floodlight configuration ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_floodlight_activity_group(profile_id, floodlight_config_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new floodlight activity group resource to insert. - activity_group = - DfareportingUtils::API_NAMESPACE::FloodlightActivityGroup.new( - floodlight_configuration_id: floodlight_config_id, - name: - format('Example Floodlight Activity Group #%s', SecureRandom.hex(3)), - type: 'COUNTER' - ) - - # Insert the floodlight activity group. - result = service.insert_floodlight_activity_group(profile_id, activity_group) - - # Display results. - puts format('Created floodlight activity group with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :floodlight_config_id) - - create_floodlight_activity_group(args[:profile_id], - args[:floodlight_config_id]) -end diff --git a/ruby/v3.4/floodlight/download_floodlight_tag.rb b/ruby/v3.4/floodlight/download_floodlight_tag.rb deleted file mode 100755 index 74df834..0000000 --- a/ruby/v3.4/floodlight/download_floodlight_tag.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example downloads activity tags for a given floodlight activity. - -require_relative '../dfareporting_utils' - -def download_floodlight_tag(profile_id, activity_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct the request. - result = service.generatetag_floodlight_activity(profile_id, - floodlight_activity_id: activity_id) - - if result.global_site_tag_global_snippet.nil? - # This is an image or iframe tag. - puts format("Floodlight activity tag:\n\n%s", - result.floodlight_activity_tag) - else - # This is a global site tag, display both the global and event snippets. - puts format("Global site tag global snippet:\n\n%s", - result.global_site_tag_global_snippet) - puts format("\n\nGlobal site tag event snippet:\n\n%s", - result.floodlight_activity_tag) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :activity_id) - - download_floodlight_tag(args[:profile_id], args[:activity_id]) -end diff --git a/ruby/v3.4/floodlight/get_floodlight_activities.rb b/ruby/v3.4/floodlight/get_floodlight_activities.rb deleted file mode 100755 index c1dbfce..0000000 --- a/ruby/v3.4/floodlight/get_floodlight_activities.rb +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays floodlight activities for a given advertiser. -# -# To create an advertiser, run create_advertiser.rb. - -require_relative '../dfareporting_utils' - -def get_floodlight_activities(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_floodlight_activities(profile_id, - advertiser_id: advertiser_id, - page_token: token, - fields: 'nextPageToken,floodlightActivities(id,name)') - - # Display results. - if result.floodlight_activities.any? - result.floodlight_activities.each do |activity| - puts format('Found floodlight activity with ID %d and name "%s".', - activity.id, activity.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_floodlight_activities(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/floodlight/get_floodlight_activity_groups.rb b/ruby/v3.4/floodlight/get_floodlight_activity_groups.rb deleted file mode 100755 index 5015c48..0000000 --- a/ruby/v3.4/floodlight/get_floodlight_activity_groups.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays floodlight activity groups for a given advertiser. -# -# To create an advertiser, run create_advertiser.rb. - -require_relative '../dfareporting_utils' - -def get_floodlight_activity_groups(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_floodlight_activity_groups(profile_id, - advertiser_id: advertiser_id, - page_token: token, - fields: 'nextPageToken,floodlightActivityGroups(id,name)') - - # Display results. - if result.floodlight_activity_groups.any? - result.floodlight_activity_groups.each do |group| - puts format( - 'Found floodlight activity group with ID %d and name "%s".', - group.id, group.name - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_floodlight_activity_groups(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/misc/get_change_logs_for_advertiser.rb b/ruby/v3.4/misc/get_change_logs_for_advertiser.rb deleted file mode 100755 index 81866ea..0000000 --- a/ruby/v3.4/misc/get_change_logs_for_advertiser.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays the change logs of a specified advertiser object. -# -# A similar pattern can be applied to get change logs for many other object -# types. - -require_relative '../dfareporting_utils' - -def get_change_logs_for_advertiser(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_change_logs(profile_id, - object_ids: [advertiser_id], - object_type: 'OBJECT_ADVERTISER', - page_token: token, - fields: 'nextPageToken,changeLogs(action,fieldName,oldValue,newValue)') - - # Display results. - if result.change_logs.any? - result.change_logs.each do |log| - puts format('%s: Field "%s" from "%s" to "%s".', log.action, - log.field_name, log.old_value, log.new_value) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_change_logs_for_advertiser(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/misc/get_sites.rb b/ruby/v3.4/misc/get_sites.rb deleted file mode 100755 index 2dc8824..0000000 --- a/ruby/v3.4/misc/get_sites.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all existing sites for the current DCM account. - -require_relative '../dfareporting_utils' - -def get_subaccounts(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_sites(profile_id, - page_token: token, - fields: 'nextPageToken,sites(id,keyName)') - - # Display results. - if result.sites.any? - result.sites.each do |site| - puts format('Found site with ID %d and key name "%s".', - site.id, site.key_name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_subaccounts(args[:profile_id]) -end diff --git a/ruby/v3.4/misc/get_size.rb b/ruby/v3.4/misc/get_size.rb deleted file mode 100755 index f511d4a..0000000 --- a/ruby/v3.4/misc/get_size.rb +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all sizes for a given width and height. - -require_relative '../dfareporting_utils' - -def get_size(profile_id, width, height) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct and execute the size request. - result = service.list_sizes(profile_id, - height: height, - width: width) - - result.sizes.each do |size| - puts format('Found size with ID %d.', size.id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :width, :height) - - get_size(args[:profile_id], args[:width], args[:height]) -end diff --git a/ruby/v3.4/placements/create_content_category.rb b/ruby/v3.4/placements/create_content_category.rb deleted file mode 100755 index ace2e2e..0000000 --- a/ruby/v3.4/placements/create_content_category.rb +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a content category with the given name and description. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_content_category(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new content category resource to insert. - content_category = DfareportingUtils::API_NAMESPACE::ContentCategory.new( - name: format('Example Content Category #%s', SecureRandom.hex(3)) - ) - - # Insert the content category. - result = service.insert_content_category(profile_id, content_category) - - # Display results. - puts format('Created content category with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_content_category(args[:profile_id]) -end diff --git a/ruby/v3.4/placements/create_placement.rb b/ruby/v3.4/placements/create_placement.rb deleted file mode 100755 index aedf5ac..0000000 --- a/ruby/v3.4/placements/create_placement.rb +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an agency paid regular placement in a given campaign. -# -# Requires the DCM site ID and campaign ID in which the placement will be -# created. To create a campaign, run create_campaign.rb. To get DCM site ID, -# run get_site.rb. - -require_relative '../dfareporting_utils' - -def create_placement(profile_id, campaign_id, site_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the campaign. - campaign = service.get_campaign(profile_id, campaign_id) - - # Create a new placement resource to insert. - placement = DfareportingUtils::API_NAMESPACE::Placement.new( - campaign_id: campaign_id, - compatibility: 'DISPLAY', - name: 'Example Placement', - payment_source: 'PLACEMENT_AGENCY_PAID', - site_id: site_id, - size: DfareportingUtils::API_NAMESPACE::Size.new( - height: 1, - width: 1 - ), - tag_formats: ['PLACEMENT_TAG_STANDARD'] - ) - - # Set the pricing schedule for the placement. - placement.pricing_schedule = - DfareportingUtils::API_NAMESPACE::PricingSchedule.new( - end_date: campaign.end_date, - pricing_type: 'PRICING_TYPE_CPM', - start_date: campaign.start_date - ) - - # Insert the placement strategy. - result = service.insert_placement(profile_id, placement) - - # Display results. - puts format('Created placement with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :site_id) - - create_placement(args[:profile_id], args[:campaign_id], args[:site_id]) -end diff --git a/ruby/v3.4/placements/create_placement_group.rb b/ruby/v3.4/placements/create_placement_group.rb deleted file mode 100755 index 43dc8aa..0000000 --- a/ruby/v3.4/placements/create_placement_group.rb +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a placement group in a given campaign. -# -# Requires the DCM site ID and campaign ID in which the placement group will be -# created. To create a campaign, run create_campaign.rb. To get DCM site ID, -# run get_site.rb. - -require_relative '../dfareporting_utils' - -def create_placement_group(profile_id, campaign_id, site_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the campaign. - campaign = service.get_campaign(profile_id, campaign_id) - - # Create a new placement group resource to insert. - placement_group = DfareportingUtils::API_NAMESPACE::PlacementGroup.new( - campaign_id: campaign_id, - name: 'Example Placement Group', - placement_group_type: 'PLACEMENT_PACKAGE', - pricing_schedule: DfareportingUtils::API_NAMESPACE::PricingSchedule.new( - start_date: campaign.start_date, - end_date: campaign.end_date, - pricing_type: 'PRICING_TYPE_CPM' - ), - site_id: site_id - ) - - # Insert the placement strategy. - result = service.insert_placement_group(profile_id, placement_group) - - # Display results. - puts format('Created placement group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :site_id) - - create_placement_group(args[:profile_id], args[:campaign_id], args[:site_id]) -end diff --git a/ruby/v3.4/placements/create_placement_strategy.rb b/ruby/v3.4/placements/create_placement_strategy.rb deleted file mode 100755 index 78b54b9..0000000 --- a/ruby/v3.4/placements/create_placement_strategy.rb +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a placement strategy with the given name. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_placement_strategy(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new placement strategy resource to insert. - strategy = DfareportingUtils::API_NAMESPACE::PlacementStrategy.new( - name: format('Example Placement Strategy #%s', SecureRandom.hex(3)) - ) - - # Insert the placement strategy. - result = service.insert_placement_strategy(profile_id, strategy) - - # Display results. - puts format('Created placement strategy with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_placement_strategy(args[:profile_id]) -end diff --git a/ruby/v3.4/placements/download_placement_tags.rb b/ruby/v3.4/placements/download_placement_tags.rb deleted file mode 100755 index 3b42efe..0000000 --- a/ruby/v3.4/placements/download_placement_tags.rb +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example downloads HTML Tags for a given campaign and placement ID. -# -# To create campaigns, run create_campaign.rb. To create placements, run -# create_placement.rb. - -require_relative '../dfareporting_utils' - -def download_placement_tags(profile_id, campaign_id, placement_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct the request. - result = service.generate_placement_tags(profile_id, - campaign_id: campaign_id, - placement_ids: [placement_id]) - - result.placement_tags.each do |tag| - tag.tag_datas.each do |data| - puts format("%s - %s\n\n", tag.placement_id, data.format) - puts format("%s\n\n", data.impression_tag) unless data.impression_tag.nil? - puts format("%s\n\n", data.click_tag) unless data.click_tag.nil? - end - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :placement_id) - - download_placement_tags(args[:profile_id], args[:campaign_id], - args[:placement_id]) -end diff --git a/ruby/v3.4/placements/get_content_categories.rb b/ruby/v3.4/placements/get_content_categories.rb deleted file mode 100755 index 018fc91..0000000 --- a/ruby/v3.4/placements/get_content_categories.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all available content categories. - -require_relative '../dfareporting_utils' - -def get_content_categories(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_content_categories(profile_id, - page_token: token, - fields: 'nextPageToken,contentCategories(id,name)') - - # Display results. - if result.content_categories.any? - result.content_categories.each do |category| - puts format('Found content category with ID %d and name "%s".', - category.id, category.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_content_categories(args[:profile_id]) -end diff --git a/ruby/v3.4/placements/get_placement_strategies.rb b/ruby/v3.4/placements/get_placement_strategies.rb deleted file mode 100755 index 60670ba..0000000 --- a/ruby/v3.4/placements/get_placement_strategies.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all available placement strategies. - -require_relative '../dfareporting_utils' - -def get_placement_strategies(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_placement_strategies(profile_id, - page_token: token, - fields: 'nextPageToken,placementStrategies(id,name)') - - # Display results. - if result.placement_strategies.any? - result.placement_strategies.each do |strategy| - puts format('Found placement strategy with ID %d and name "%s".', - strategy.id, strategy.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_placement_strategies(args[:profile_id]) -end diff --git a/ruby/v3.4/placements/get_placements.rb b/ruby/v3.4/placements/get_placements.rb deleted file mode 100755 index dc9721f..0000000 --- a/ruby/v3.4/placements/get_placements.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all available placements. - -require_relative '../dfareporting_utils' - -def get_placements(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_placements(profile_id, - page_token: token, - fields: 'nextPageToken,placements(campaignId,id,name)') - - # Display results. - if result.placements.any? - result.placements.each do |placement| - puts format( - 'Found placement with ID %d and name "%s" for campaign %d.', - placement.id, placement.name, placement.campaign_id - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_placements(args[:profile_id]) -end diff --git a/ruby/v3.4/remarketing/create_remarketing_list.rb b/ruby/v3.4/remarketing/create_remarketing_list.rb deleted file mode 100755 index c52fff0..0000000 --- a/ruby/v3.4/remarketing/create_remarketing_list.rb +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a remarketing list for a given advertiser and floodight -# activity, using a custom rule. -# -# Note: this sample assumes that the floodlight activity specified has a U1 -# custom floodlight variable. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_remarketing_list(profile_id, advertiser_id, floodlight_activity_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a list population term. - # This term matches all visitors with a U1 value exactly matching - # "test_value" - term = DfareportingUtils::API_NAMESPACE::ListPopulationTerm.new( - operator: 'STRING_EQUALS', - type: 'CUSTOM_VARIABLE_TERM', - value: 'test_value', - variable_name: 'U1' - ) - - # Add the term to a clause and the clause to a population rule. - # This rule will target all visitors who trigger the specified floodlight - # activity and satisfy the custom rule defined in the list population term. - rule = DfareportingUtils::API_NAMESPACE::ListPopulationRule.new( - floodlight_activity_id: floodlight_activity_id, - list_population_clauses: [ - DfareportingUtils::API_NAMESPACE::ListPopulationClause.new( - terms: [term] - ) - ] - ) - - # Create the remarketing list. - list = DfareportingUtils::API_NAMESPACE::RemarketingList.new( - name: format('Test remarketing list #%s', SecureRandom.hex(3)), - active: true, - advertiser_id: advertiser_id, - life_span: 30, - list_population_rule: rule - ) - - # Insert the remarketing list. - list = service.insert_remarketing_list(profile_id, list) - - # Display results. - puts format('Remarketing list with ID %d and name "%s" was created.', - list.id, list.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :floodlight_activity_id) - - create_remarketing_list(args[:profile_id], args[:advertiser_id], - args[:floodlight_activity_id]) -end diff --git a/ruby/v3.4/remarketing/get_remarketing_lists.rb b/ruby/v3.4/remarketing/get_remarketing_lists.rb deleted file mode 100755 index 776837d..0000000 --- a/ruby/v3.4/remarketing/get_remarketing_lists.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Displays all remarketing lists owned by the specified advertiser. -# -# Note: the RemarketingLists resource will only return lists owned by the -# specified advertiser. To see all lists that can be used for targeting ads -# (including those shared from other accounts or advertisers), use the -# TargetableRemarketingLists resource instead. - -require_relative '../dfareporting_utils' - -def get_remarketing_lists(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_remarketing_lists(profile_id, advertiser_id, - page_token: token, - fields: 'nextPageToken,remarketingLists(id,name)') - - # Display results. - if result.remarketing_lists.any? - result.remarketing_lists.each do |list| - puts format('Found remarketing list with ID %d and name "%s".', - list.id, list.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_remarketing_lists(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/remarketing/share_remarketing_list_to_advertiser.rb b/ruby/v3.4/remarketing/share_remarketing_list_to_advertiser.rb deleted file mode 100755 index 4b201bc..0000000 --- a/ruby/v3.4/remarketing/share_remarketing_list_to_advertiser.rb +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example shares an existing remarketing list with the specified -# advertiser. - -require_relative '../dfareporting_utils' - -def share_remarketing_list_to_advertiser(profile_id, advertiser_id, - remarketing_list_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Load the existing share info. - share = service.get_remarketing_list_share(profile_id, remarketing_list_id) - share.shared_advertiser_ids ||= [] - - if share.shared_advertiser_ids.include?(advertiser_id) - puts format('Remarketing list %d is already shared to advertiser %d.', - remarketing_list_id, advertiser_id) - else - share.shared_advertiser_ids <<= advertiser_id - - # Update the share info with the newly added advertiser ID. - share = service.update_remarketing_list_share(profile_id, share) - - puts format('Remarketing list %d is now shared to advertiser ID(s): %s', - remarketing_list_id, share.shared_advertiser_ids.join(', ')) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :remarketing_list_id) - - share_remarketing_list_to_advertiser(args[:profile_id], args[:advertiser_id], - args[:remarketing_list_id]) -end diff --git a/ruby/v3.4/remarketing/target_ad_to_remarketing_list.rb b/ruby/v3.4/remarketing/target_ad_to_remarketing_list.rb deleted file mode 100755 index c7b8230..0000000 --- a/ruby/v3.4/remarketing/target_ad_to_remarketing_list.rb +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example targets an ad to a remarketing list. -# -# The first targetable remarketing list, either owned by or shared to the ad's -# advertiser, will be used. To create a remarketing list, see -# create_remarketing_list.rb. To share a remarketing list with the ad's -# advertiser, see share_remarketing_list_to_advertiser.rb. - -require_relative '../dfareporting_utils' - -def target_ad_to_remarketing_list(profile_id, ad_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the ad. - ad = service.get_ad(profile_id, ad_id) - - # Retrieve a single targetable remarketing list for the ad. - lists = service.list_targetable_remarketing_lists(profile_id, - ad.advertiser_id, max_results: 1) - - if lists.targetable_remarketing_lists.any? - list = lists.targetable_remarketing_lists.first - - # Update the ad with a list targeting expression. - ad.remarketing_list_expression = - DfareportingUtils::API_NAMESPACE::ListTargetingExpression.new( - expression: list.id - ) - - ad = service.update_ad(profile_id, ad) - - puts format('Ad %d updated to use remarketing list expression: "%s".', - ad.id, ad.remarketing_list_expression.expression) - else - puts format('No targetable remarketing lists found for ad with ID %d.', - ad_id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :ad_id) - - target_ad_to_remarketing_list(args[:profile_id], args[:ad_id]) -end diff --git a/ruby/v3.4/reports/create_report.rb b/ruby/v3.4/reports/create_report.rb deleted file mode 100755 index 02c51b1..0000000 --- a/ruby/v3.4/reports/create_report.rb +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# An end-to-end example of how to create and configure a standard report. - -require_relative '../dfareporting_utils' -require 'date' - -def create_report(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # 1. Create a report resource. - report = create_report_resource - - # 2. Define report criteria. - define_report_criteria(report) - - # 3. (optional) Look up compatible fields. - find_compatible_fields(service, profile_id, report) - - # 4. Add dimension filers to the report criteria. - add_dimension_filters(service, profile_id, report) - - # 5. Save the report resource. - insert_report_resource(service, profile_id, report) -end - -def create_report_resource - report = DfareportingUtils::API_NAMESPACE::Report.new( - # Set the required fields "name" and "type". - name: 'Example Standard Report', - type: 'STANDARD', - # Set optional fields. - file_name: 'example_report', - format: 'CSV' - ) - - puts format('Creating %s report resource with name "%s".', report.type, - report.name) - - report -end - -def define_report_criteria(report) - # Define a date range to report on. This example uses explicit start and end - # dates to mimic the "LAST_30_DAYS" relative date range. - start_date = DateTime.now.prev_day(30).strftime('%Y-%m-%d') - end_date = DateTime.now.strftime('%Y-%m-%d') - - # Create a report criteria - criteria = DfareportingUtils::API_NAMESPACE::Report::Criteria.new( - date_range: DfareportingUtils::API_NAMESPACE::DateRange.new( - start_date: start_date, - end_date: end_date - ), - dimensions: [ - DfareportingUtils::API_NAMESPACE::SortedDimension.new( - name: 'advertiser' - ) - ], - metric_names: ['clicks', 'impressions'] - ) - - # Add the criteria to the report resource. - report.criteria = criteria - - puts format("\nAdded report criteria:\n%s", criteria.to_json) -end - -def find_compatible_fields(service, profile_id, report) - fields = service.query_report_compatible_field(profile_id, report) - - report_fields = fields.report_compatible_fields - - if report_fields.dimensions.any? - # Add a compatible dimension to the report. - report.criteria.dimensions << - DfareportingUtils::API_NAMESPACE::SortedDimension.new( - name: report_fields.dimensions.first.name - ) - elsif report_fields.metrics.any? - # Add a compatible metric to the report. - report.criteria.metric_names << report_fields.metrics.first.name - end - - puts format("\nUpdated report criteria (with compatible fields):\n%s", - report.criteria.to_json) -end - -def add_dimension_filters(service, profile_id, report) - # Query advertiser dimension values for report run dates. - dimension = DfareportingUtils::API_NAMESPACE::DimensionValueRequest.new( - dimension_name: 'advertiser', - start_date: report.criteria.date_range.start_date, - end_date: report.criteria.date_range.end_date - ) - - values = service.query_dimension_value(profile_id, dimension) - - unless values.items.empty? - # Add a value as a filter to the report criteria. - report.criteria.dimension_filters = [values.items.first] - end - - puts format("\nUpdated report criteria (with valid dimension filters):\n%s", - report.criteria.to_json) -end - -def insert_report_resource(service, profile_id, report) - report = service.insert_report(profile_id, report) - - puts format("\nSuccessfully inserted new report with ID %s.", report.id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_report(args[:profile_id]) -end diff --git a/ruby/v3.4/reports/delete_report.rb b/ruby/v3.4/reports/delete_report.rb deleted file mode 100755 index 1947df4..0000000 --- a/ruby/v3.4/reports/delete_report.rb +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to delete a report. - -require_relative '../dfareporting_utils' - -def delete_report(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Delete the report. - service.delete_report(profile_id, report_id) - - puts format('Successfully deleted report with ID %d.', report_id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - delete_report(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.4/reports/download_file.rb b/ruby/v3.4/reports/download_file.rb deleted file mode 100755 index 671ce68..0000000 --- a/ruby/v3.4/reports/download_file.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to download a file - -require_relative '../dfareporting_utils' - -def download_file(report_id, file_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the file metadata. - report_file = service.get_file(report_id, file_id) - return unless report_file.status == 'REPORT_AVAILABLE' - - # Prepare a local file to download the report contents to. - File.open(generate_file_name(report_file), 'w') do |out_file| - # Execute the download request. Providing a download destination - # retrieves the file contents rather than the file metadata. - service.get_file(report_id, file_id, download_dest: out_file) - - puts format('File %s downloaded to %s', file_id, - File.absolute_path(out_file.path)) - end -end - -def generate_file_name(report_file) - file_name = report_file.file_name - # If no filename is specified, use the file ID instead. - file_name = report_file.id.to_s if file_name.empty? - extension = report_file.format == 'CSV' ? '.csv' : '.xml' - file_name + extension -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :report_id, :file_id) - - download_file(args[:report_id], args[:file_id]) -end diff --git a/ruby/v3.4/reports/find_and_download_file.rb b/ruby/v3.4/reports/find_and_download_file.rb deleted file mode 100755 index a7f93a3..0000000 --- a/ruby/v3.4/reports/find_and_download_file.rb +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2018, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# An end-to-end example of how to find and download a report file. - -require_relative '../dfareporting_utils' - -def find_and_download_file(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # 1. Find a file to download. - report_file = find_file(service, profile_id, report_id) - - if report_file - # 2. (optional) Generate a browser URL. - generate_browser_url(service, report_id, report_file.id) - - # 3. Directly download the file. - direct_download_file(service, report_id, report_file.id) - else - puts format('No file found for profile ID %d and report ID %d.', - profile_id, report_id) - end -end - -def find_file(service, profile_id, report_id) - page_token = nil - target = nil - - loop do - result = service.list_report_files(profile_id, report_id, - page_token: page_token) - - result.items.each do |file| - if target_file?(file) - target = file - break - end - end - - page_token = (result.next_page_token if target.nil? && result.items.any?) - break if page_token.to_s.empty? - end - - if target - puts format('Found file %s with filename "%s".', target.id, - target.file_name) - return target - end - - puts format('Unable to find file for profile ID %d and report ID %d.', - profile_id, report_id) - nil -end - -def target_file?(file) - # Provide custom validation logic here. - # For example purposes, any available file is considered valid. - file.status == 'REPORT_AVAILABLE' -end - -def generate_browser_url(service, report_id, file_id) - report_file = service.get_file(report_id, file_id) - browser_url = report_file.urls.browser_url - - puts format('File %s has browser URL: %s.', report_file.id, browser_url) -end - -def direct_download_file(service, report_id, file_id) - # Retrieve the file metadata. - report_file = service.get_file(report_id, file_id) - return unless report_file.status == 'REPORT_AVAILABLE' - - # Prepare a local file to download the report contents to. - File.open(generate_file_name(report_file), 'w') do |out_file| - # Execute the download request. Providing a download destination - # retrieves the file contents rather than the file metadata. - service.get_file(report_id, file_id, download_dest: out_file) - - puts format('File %s downloaded to %s', file_id, - File.absolute_path(out_file.path)) - end -end - -def generate_file_name(report_file) - file_name = report_file.file_name - # If no filename is specified, use the file ID instead. - file_name = report_file.id.to_s if file_name.empty? - extension = report_file.format == 'CSV' ? '.csv' : '.xml' - file_name + extension -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - find_and_download_file(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.4/reports/find_and_run_report.rb b/ruby/v3.4/reports/find_and_run_report.rb deleted file mode 100755 index 439cb35..0000000 --- a/ruby/v3.4/reports/find_and_run_report.rb +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright (C) 2016 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# An end-to-end example of how to find and run a report. - -require_relative '../dfareporting_utils' - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - -def find_and_run_report(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # 1. Find a report to run. - report = find_report(service, profile_id) - - if report - # 2. Run the report. - report_file = run_report(service, profile_id, report.id) - - # 3. Wait for the report file to be ready. - wait_for_report_file(service, report.id, report_file.id) - else - puts format('No report found for profile ID %d.', profile_id) - end -end - -def find_report(service, profile_id) - page_token = nil - target = nil - - loop do - result = service.list_reports(profile_id, page_token: page_token) - - result.items.each do |report| - if target_report?(report) - target = report - break - end - end - - page_token = (result.next_page_token if target.nil? && result.items.any?) - break if page_token.to_s.empty? - end - - if target - puts format('Found report %s with filename "%s".', target.id, - target.file_name) - return target - end - - puts format('Unable to find report for profile ID %d.', profile_id) - nil -end - -def target_report?(report) - # Provide custom validation logic here. - # For example purposes, any report is considered valid. - !report.nil? -end - -def run_report(service, profile_id, report_id) - # Run the report. - report_file = service.run_report(profile_id, report_id) - - puts format('Running report %d, current file status is %s.', report_id, - report_file.status) - report_file -end - -def wait_for_report_file(service, report_id, file_id) - # Wait for the report file to finish processing. - # An exponential backoff strategy is used to conserve request quota. - interval = 0 - start_time = Time.now - loop do - report_file = service.get_file(report_id, file_id) - - status = report_file.status - if status == 'REPORT_AVAILABLE' - puts format('File status is %s, ready to download.', status) - break - elsif status != 'PROCESSING' - puts format('File status is %s, processing failed.', status) - break - elsif Time.now - start_time > MAX_RETRY_ELAPSED_TIME - puts 'File processing deadline exceeded.' - break - end - - interval = next_sleep_interval(interval) - puts format('File status is %s, sleeping for %d seconds.', status, - interval) - sleep(interval) - end -end - -def next_sleep_interval(previous_interval) - min_interval = [MIN_RETRY_INTERVAL, previous_interval].max - max_interval = [MIN_RETRY_INTERVAL, previous_interval * 3].max - [MAX_RETRY_INTERVAL, rand(min_interval..max_interval)].min -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - find_and_run_report(args[:profile_id]) -end diff --git a/ruby/v3.4/reports/get_compatible_fields.rb b/ruby/v3.4/reports/get_compatible_fields.rb deleted file mode 100755 index 548bace..0000000 --- a/ruby/v3.4/reports/get_compatible_fields.rb +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to get the compatible fields for a report. - -require_relative '../dfareporting_utils' - -def get_compatible_fields(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Get the report. - report = service.get_report(profile_id, report_id) - - # Get the compatible fields. - result = service.query_report_compatible_field(profile_id, report) - - compatible_fields = result.report_compatible_fields - - # Display dimensions. - dimensions = compatible_fields.dimensions.map(&:name) - print_fields('Dimensions', dimensions) - - # Display metrics. - metrics = compatible_fields.metrics.map(&:name) - print_fields('Metrics', metrics) - - # Display dimension filters. - filters = compatible_fields.dimension_filters.map(&:name) - print_fields('Dimension Filers', filters) - - # Display pivoted activity metrics. - activities = compatible_fields.pivoted_activity_metrics.map(&:name) - print_fields('Pivoted Activity Metrics', activities) -end - -def print_fields(type, fields) - puts format('Compatible %s', type) - puts fields.join(', ') - puts -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - get_compatible_fields(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.4/reports/get_dimension_values.rb b/ruby/v3.4/reports/get_dimension_values.rb deleted file mode 100755 index b2f9ed6..0000000 --- a/ruby/v3.4/reports/get_dimension_values.rb +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all values for a dimension - -require_relative '../dfareporting_utils' -require 'date' - -def get_dimension_values(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create the dimension to query. - dimension = DfareportingUtils::API_NAMESPACE::DimensionValueRequest.new( - dimension_name: 'advertiser', - start_date: DateTime.now.prev_year.strftime('%Y-%m-%d'), - end_date: DateTime.now.strftime('%Y-%m-%d') - ) - - token = nil - loop do - result = service.query_dimension_value( - profile_id, dimension, - page_token: token, - fields: 'nextPageToken,items(id,value)' - ) - - # Display results. - if result.items.any? - result.items.each do |dimension_value| - puts format('Dimension with ID %d and value "%s" was found.', - dimension_value.id, dimension_value.value) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_dimension_values(args[:profile_id]) -end diff --git a/ruby/v3.4/reports/get_files.rb b/ruby/v3.4/reports/get_files.rb deleted file mode 100755 index e2a444e..0000000 --- a/ruby/v3.4/reports/get_files.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all files for a profile - -require_relative '../dfareporting_utils' - -def get_files(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_files(profile_id, - page_token: token, - fields: 'nextPageToken,items(fileName,id,status)') - - # Display results. - if result.items.any? - result.items.each do |file| - puts format( - 'Report file with ID %d and file name "%s" has status "%s".', - file.id, file.file_name, file.status - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_files(args[:profile_id]) -end diff --git a/ruby/v3.4/reports/get_report_files.rb b/ruby/v3.4/reports/get_report_files.rb deleted file mode 100755 index 9a7e027..0000000 --- a/ruby/v3.4/reports/get_report_files.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all files for a report - -require_relative '../dfareporting_utils' - -def get_report_files(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_report_files(profile_id, report_id, - page_token: token, - fields: 'nextPageToken,items(fileName,id,status)') - - # Display results. - if result.items.any? - result.items.each do |file| - puts format( - 'Report file with ID %d and file name "%s" has status "%s".', - file.id, file.file_name, file.status - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - get_report_files(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.4/reports/get_reports.rb b/ruby/v3.4/reports/get_reports.rb deleted file mode 100755 index 9dd22f3..0000000 --- a/ruby/v3.4/reports/get_reports.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all reports for a profile - -require_relative '../dfareporting_utils' - -def get_reports(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_reports(profile_id, - page_token: token, - fields: 'nextPageToken,items(id,name,type)') - - # Display results. - if result.items.any? - result.items.each do |report| - puts format('%s report with ID %d and name "%s" was found.', - report.type, report.id, report.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_reports(args[:profile_id]) -end diff --git a/ruby/v3.4/reports/run_report.rb b/ruby/v3.4/reports/run_report.rb deleted file mode 100755 index fe771a1..0000000 --- a/ruby/v3.4/reports/run_report.rb +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright (C) 2016 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to run a report. - -require_relative '../dfareporting_utils' - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - -def run_report(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Run the report. - report_file = service.run_report(profile_id, report_id) - puts format('File with ID %s has been created.', report_file.id) - - # Wait for the report to finish processing. - wait_for_report_file(service, report_id, report_file.id) -end - -def wait_for_report_file(service, report_id, file_id) - # An exponential backoff strategy is used to conserve request quota. - interval = 0 - start_time = Time.now - loop do - report_file = service.get_file(report_id, file_id) - - status = report_file.status - if status == 'REPORT_AVAILABLE' - puts format('File status is %s, ready to download.', status) - break - elsif status != 'PROCESSING' - puts format('File status is %s, processing failed.', status) - break - elsif Time.now - start_time > MAX_RETRY_ELAPSED_TIME - puts 'File processing deadline exceeded.' - break - end - - interval = next_sleep_interval(interval) - puts format('File status is %s, sleeping for %d seconds.', status, interval) - sleep(interval) - end -end - -def next_sleep_interval(previous_interval) - min_interval = [MIN_RETRY_INTERVAL, previous_interval].max - max_interval = [MIN_RETRY_INTERVAL, previous_interval * 3].max - [MAX_RETRY_INTERVAL, rand(min_interval..max_interval)].min -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - run_report(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.4/subaccounts/create_subaccount.rb b/ruby/v3.4/subaccounts/create_subaccount.rb deleted file mode 100755 index 0516b31..0000000 --- a/ruby/v3.4/subaccounts/create_subaccount.rb +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a subaccount in a given DCM account. -# -# To get the account ID, run get_all_userprofiles.rb. To get the available -# permissions, run get_subaccount_permissions.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_subaccount(profile_id, account_id, permission_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new subaccount resource to insert. - subaccount = DfareportingUtils::API_NAMESPACE::Subaccount.new( - account_id: account_id, - available_permission_ids: [permission_id], - name: format('Example Subaccount #%s', SecureRandom.hex(3)) - ) - - # Insert the subaccount. - result = service.insert_subaccount(profile_id, subaccount) - - # Display results. - puts format('Created subaccount with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :account_id, - :permission_id) - - create_subaccount(args[:profile_id], args[:account_id], args[:permission_id]) -end diff --git a/ruby/v3.4/subaccounts/get_subaccount_permissions.rb b/ruby/v3.4/subaccounts/get_subaccount_permissions.rb deleted file mode 100755 index 23559ee..0000000 --- a/ruby/v3.4/subaccounts/get_subaccount_permissions.rb +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all of the available user role permissions for a given -# subaccount. -# -# To get a subaccount ID, run get_subaccounts.rb. - -require_relative '../dfareporting_utils' - -def get_subaccount_permissions(profile_id, subaccount_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct and execute the subaccount request. - subaccount = service.get_subaccount(profile_id, subaccount_id) - - # Construct the user role permissions request. - result = service.list_user_role_permissions(profile_id, - ids: subaccount.available_permission_ids) - - result.user_role_permissions.each do |permission| - puts format('Found user role permission with ID %d and name "%s".', - permission.id, permission.name) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :subaccount_id) - - get_subaccount_permissions(args[:profile_id], args[:subaccount_id]) -end diff --git a/ruby/v3.4/subaccounts/get_subaccounts.rb b/ruby/v3.4/subaccounts/get_subaccounts.rb deleted file mode 100755 index a18a9b1..0000000 --- a/ruby/v3.4/subaccounts/get_subaccounts.rb +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all subaccounts. -# -# Note that the permissions assigned to a subaccount are not returned in a -# human-readable format with this example. Run get_available_permissions.rb to -# see what permissions are available on a subaccount. - -require_relative '../dfareporting_utils' - -def get_subaccounts(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_subaccounts(profile_id, - page_token: token, - fields: 'nextPageToken,subaccounts(id,name)') - - # Display results. - if result.subaccounts.any? - result.subaccounts.each do |subaccount| - puts format('Found subaccount with ID %d and name "%s".', subaccount.id, - subaccount.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_subaccounts(args[:profile_id]) -end diff --git a/ruby/v3.4/targeting/configure_dynamic_asset_selection.rb b/ruby/v3.4/targeting/configure_dynamic_asset_selection.rb deleted file mode 100755 index c2596c0..0000000 --- a/ruby/v3.4/targeting/configure_dynamic_asset_selection.rb +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example enables dynamic asset selection for an in-stream video creative. -# -# Requires an existing in-stream video creative, a new video asset, and a -# targeting template ID as input. To get an in-stream video creative, run -# create_instream_video_creative.rb. To get a targeting template, run -# create_targeting_template.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def configure_dynamic_asset_selection(profile_id, creative_id, template_id, - path_to_video_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the specified creative. - creative = service.get_creative(profile_id, creative_id) - - abort 'Invalid creative specified' if - creative.nil? || (creative.type != 'INSTREAM_VIDEO') - - # Enable dynamic asset selection for the creative if necessary. - enable_dynamic_asset_selection(creative) unless - creative.dynamic_asset_selection? - - # Upload the new video asset and add it to the creative. - video_asset = CreativeAssetUtils.new(service, profile_id).upload_asset( - creative.advertiser_id, path_to_video_file, 'VIDEO' - ) - - creative.creative_assets <<= - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: video_asset.asset_identifier, - role: 'PARENT_VIDEO' - ) - - # Create a rule targeting the new video asset and add it to the creative. - creative.creative_asset_selection.rules <<= - DfareportingUtils::API_NAMESPACE::Rule.new( - asset_id: video_asset.id, - name: format('Test rule for asset %d', video_asset.id), - targeting_template_id: template_id - ) - - result = service.update_creative(profile_id, creative) - - puts format('Dynamic asset selection enabled for creative with ID %d.', - result.id) -end - -def enable_dynamic_asset_selection(creative) - # Locate an existing video asset to use as a default. - default_asset = creative.creative_assets.find do |asset| - asset.role == 'PARENT_VIDEO' - end - - abort 'Default video asset could not be found.' if default_asset.nil? - - # Enable dynamic asset selection for the creative. - creative.dynamic_asset_selection = true - - # Create a new selection using the existing asset as a default. - creative.creative_asset_selection = - DfareportingUtils::API_NAMESPACE::CreativeAssetSelection.new( - default_asset_id: default_asset.id, - rules: [] - ) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :creative_id, - :template_id, :path_to_video_file) - - configure_dynamic_asset_selection(args[:profile_id], args[:creative_id], - args[:template_id], args[:path_to_video_file]) -end diff --git a/ruby/v3.4/targeting/create_targeting_template.rb b/ruby/v3.4/targeting/create_targeting_template.rb deleted file mode 100755 index 1e1b603..0000000 --- a/ruby/v3.4/targeting/create_targeting_template.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a targeting template associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_targeting_template(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new targeting template resource to insert. - # This template will be configured to serve ads on Monday, Wednesday, and - # Friday from 9-10am and 3-5pm. - # Note: targeting template names must be unique within an advetiser. - targeting_template = DfareportingUtils::API_NAMESPACE::TargetingTemplate.new( - advertiser_id: advertiser_id, - day_part_targeting: DfareportingUtils::API_NAMESPACE::DayPartTargeting.new( - days_of_week: %w[MONDAY WEDNESDAY FRIDAY], - hours_of_day: [9, 15, 16], - user_local_time: true - ), - name: format('Test Targeting Template #%s', SecureRandom.hex(3)) - ) - - # Insert the targeting template. - result = service.insert_targeting_template(profile_id, targeting_template) - - # Display results. - puts format('Created targeting template with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_targeting_template(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.4/targeting/get_targeting_templates.rb b/ruby/v3.4/targeting/get_targeting_templates.rb deleted file mode 100755 index fffa481..0000000 --- a/ruby/v3.4/targeting/get_targeting_templates.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example retrieves all targeting templates for your DCM user profile. -# -# Displays name, ID, and advertiser ID for each targeting template found. - -require_relative '../dfareporting_utils' - -def get_targeting_templates(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_targeting_templates(profile_id, - page_token: token, - fields: 'nextPageToken,targetingTemplates(advertiserId,id,name)') - - # Display results. - if result.targeting_templates.any? - result.targeting_templates.each do |template| - puts format( - 'Found targeting template with ID %d and name "%s" associated with ' \ - 'advertiser ID %d.', template.id, template.name, - template.advertiser_id - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_targeting_templates(args[:profile_id]) -end diff --git a/ruby/v3.4/user_profiles/get_user_profiles.rb b/ruby/v3.4/user_profiles/get_user_profiles.rb deleted file mode 100755 index 6752b7b..0000000 --- a/ruby/v3.4/user_profiles/get_user_profiles.rb +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all user profiles - -require_relative '../dfareporting_utils' - -def get_user_profiles - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Get all user profiles. - result = service.list_user_profiles - - # Display results. - result.items.each do |profile| - puts format( - 'User profile with ID %d and name "%s" was found for account %d.', - profile.profile_id, profile.user_name, profile.account_id - ) - end -end - -get_user_profiles if $PROGRAM_NAME == __FILE__ diff --git a/ruby/v3.4/user_roles/create_user_role.rb b/ruby/v3.4/user_roles/create_user_role.rb deleted file mode 100755 index 2d3aecf..0000000 --- a/ruby/v3.4/user_roles/create_user_role.rb +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a user role in a given DCM account. -# -# To get the account ID, run get_all_userprofiles.rb. To get the parent user -# role ID, run get_user_roles.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_user_role(profile_id, account_id, parent_role_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new user role resource to insert. - user_role = DfareportingUtils::API_NAMESPACE::UserRole.new( - account_id: account_id, - name: format('Example User Role #%s', SecureRandom.hex(3)), - parent_user_role_id: parent_role_id - ) - - # Insert the user role. - result = service.insert_user_role(profile_id, user_role) - - # Display results. - puts format('Created user role with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :account_id, - :parent_role_id) - - create_user_role(args[:profile_id], args[:account_id], - args[:parent_role_id]) -end diff --git a/ruby/v3.4/user_roles/get_user_roles.rb b/ruby/v3.4/user_roles/get_user_roles.rb deleted file mode 100755 index 9faf8f2..0000000 --- a/ruby/v3.4/user_roles/get_user_roles.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all user roles. - -require_relative '../dfareporting_utils' - -def get_user_roles(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_user_roles(profile_id, - page_token: token, - fields: 'nextPageToken,userRoles(id,name)') - - # Display results. - if result.user_roles.any? - result.user_roles.each do |role| - puts format('Found user role with ID %d and name "%s".', role.id, - role.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_user_roles(args[:profile_id]) -end diff --git a/ruby/v3.5/Gemfile b/ruby/v3.5/Gemfile deleted file mode 100644 index 955a8c6..0000000 --- a/ruby/v3.5/Gemfile +++ /dev/null @@ -1,5 +0,0 @@ -source 'https://rubygems.org' - -gem 'google-api-client', '0.36.0' -gem 'googleauth', '>= 0.5' -gem 'google-apis-dfareporting_v3_5', '~> 0.1.0' diff --git a/ruby/v3.5/Gemfile.lock b/ruby/v3.5/Gemfile.lock deleted file mode 100644 index 73bddc4..0000000 --- a/ruby/v3.5/Gemfile.lock +++ /dev/null @@ -1,82 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - addressable (2.8.0) - public_suffix (>= 2.0.2, < 5.0) - declarative (0.0.20) - faraday (1.4.2) - faraday-em_http (~> 1.0) - faraday-em_synchrony (~> 1.0) - faraday-excon (~> 1.1) - faraday-net_http (~> 1.0) - faraday-net_http_persistent (~> 1.1) - multipart-post (>= 1.2, < 3) - ruby2_keywords (>= 0.0.4) - faraday-em_http (1.0.0) - faraday-em_synchrony (1.0.0) - faraday-excon (1.1.0) - faraday-net_http (1.0.1) - faraday-net_http_persistent (1.1.0) - google-api-client (0.36.0) - addressable (~> 2.5, >= 2.5.1) - googleauth (~> 0.9) - httpclient (>= 2.8.1, < 3.0) - mini_mime (~> 1.0) - representable (~> 3.0) - retriable (>= 2.0, < 4.0) - signet (~> 0.12) - google-apis-core (0.3.0) - addressable (~> 2.5, >= 2.5.1) - googleauth (~> 0.14) - httpclient (>= 2.8.1, < 3.0) - mini_mime (~> 1.0) - representable (~> 3.0) - retriable (>= 2.0, < 4.0) - rexml - signet (~> 0.14) - webrick - google-apis-dfareporting_v3_5 (0.1.0) - google-apis-core (~> 0.1) - googleauth (0.16.2) - faraday (>= 0.17.3, < 2.0) - jwt (>= 1.4, < 3.0) - memoist (~> 0.16) - multi_json (~> 1.11) - os (>= 0.9, < 2.0) - signet (~> 0.14) - httpclient (2.8.3) - jwt (2.2.3) - memoist (0.16.2) - mini_mime (1.1.0) - multi_json (1.15.0) - multipart-post (2.1.1) - os (1.1.1) - public_suffix (4.0.6) - representable (3.1.1) - declarative (< 0.1.0) - trailblazer-option (>= 0.1.1, < 0.2.0) - uber (< 0.2.0) - retriable (3.1.2) - rexml (3.2.5) - ruby2_keywords (0.0.4) - signet (0.15.0) - addressable (~> 2.3) - faraday (>= 0.17.3, < 2.0) - jwt (>= 1.5, < 3.0) - multi_json (~> 1.10) - trailblazer-option (0.1.1) - uber (0.1.0) - webrick (1.7.0) - -PLATFORMS - universal-darwin-20 - x86_64-linux - -DEPENDENCIES - google-api-client (= 0.36.0) - google-apis-dfareporting_v3_5 (~> 0.1.0) - googleauth (>= 0.5) - -BUNDLED WITH - 2.2.18 - diff --git a/ruby/v3.5/README.md b/ruby/v3.5/README.md deleted file mode 100644 index 58b8c58..0000000 --- a/ruby/v3.5/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# DCM/DFA Reporting and Trafficking API Ruby Samples - -This is a collection of samples written in Ruby which provide a starting place -for your experimentation into the DCM/DFA Reporting and Trafficking API. - -## Prerequisites - -Please make sure that you're running Ruby 1.9+ and you've run -`bundle install` on the example directory to install all prerequisites. - -## Setup Authentication - -This API uses OAuth 2.0. Learn more about Google APIs and OAuth 2.0 here: -https://developers.google.com/accounts/docs/OAuth2 - -Or, if you'd like to dive right in, follow these steps. - - Visit https://console.developers.google.com to register your application. - - From the API Manager -> Google APIs screen, activate access to "DCM/DFA Reporting and Trafficking API". - - Click on "Credentials" in the left navigation menu - - Click the button labeled "Create credentials" and select "OAuth Client ID" - - Select "Other" as the "Application type", then "Create" - - From the Credentials page, click "Download JSON" next to the client ID you just created and save the file as `client_secrets.json` in the samples project directory - -## Running the Examples - -I'm assuming you've checked out the code and are reading this from a local -directory. If not check out the code to a local directory. - -1. Start up a sample, e.g. - - $ bundle exec ruby create_report.rb - -2. Complete the authorization steps on your browser - -3. Examine your shell output, be inspired and start hacking an amazing new app! diff --git a/ruby/v3.5/ads/create_rotation_group.rb b/ruby/v3.5/ads/create_rotation_group.rb deleted file mode 100755 index dda13a5..0000000 --- a/ruby/v3.5/ads/create_rotation_group.rb +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a rotation group ad in a given campaign. - -require_relative '../dfareporting_utils' - -def create_rotation_group(profile_id, campaign_id, placement_id, creative_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the campaign (to get end date). - campaign = service.get_campaign(profile_id, campaign_id) - - # Construct creative assignment. - creative_assignment = - DfareportingUtils::API_NAMESPACE::CreativeAssignment.new( - active: true, - creative_id: creative_id, - click_through_url: DfareportingUtils::API_NAMESPACE::ClickThroughUrl.new( - default_landing_page: true - ) - ) - - # Construct placement assignment. - placement_assignment = - DfareportingUtils::API_NAMESPACE::PlacementAssignment.new( - active: true, - placement_id: placement_id - ) - - # Construct creative rotation. - creative_rotation = DfareportingUtils::API_NAMESPACE::CreativeRotation.new( - creative_assignments: [creative_assignment], - type: 'CREATIVE_ROTATION_TYPE_RANDOM', - weight_calculation_strategy: 'WEIGHT_STRATEGY_OPTIMIZED' - ) - - # Construct delivery schedule. - delivery_schedule = DfareportingUtils::API_NAMESPACE::DeliverySchedule.new( - impression_ratio: 1, - priority: 'AD_PRIORITY_01' - ) - - # Construct and save ad. - ad = DfareportingUtils::API_NAMESPACE::Ad.new( - active: true, - campaign_id: campaign_id, - creative_rotation: creative_rotation, - delivery_schedule: delivery_schedule, - end_time: format('%sT00:00:00Z', campaign.end_date), - name: 'Example Rotation Group', - placement_assignments: [placement_assignment], - start_time: format('%sT23:59:59Z', Time.now.strftime('%Y-%m-%d')), - type: 'AD_SERVING_STANDARD_AD' - ) - - result = service.insert_ad(profile_id, ad) - - puts format('Created rotation group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :placement_id, :creative_id) - - create_rotation_group(args[:profile_id], args[:campaign_id], - args[:placement_id], args[:creative_id]) -end diff --git a/ruby/v3.5/ads/get_ads.rb b/ruby/v3.5/ads/get_ads.rb deleted file mode 100755 index 642d565..0000000 --- a/ruby/v3.5/ads/get_ads.rb +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all active ads your DCM user profile can see. -# -# Only name and ID are returned. - -require_relative '../dfareporting_utils' - -def get_ads(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_ads(profile_id, - page_token: token, - fields: 'nextPageToken,ads(id,name)') - - # Display results. - if result.ads.any? - result.ads.each do |ad| - puts format('Found ad with ID %d and name "%s".', ad.id, ad.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_ads(args[:profile_id]) -end diff --git a/ruby/v3.5/advertisers/assign_advertiser_to_advertiser_group.rb b/ruby/v3.5/advertisers/assign_advertiser_to_advertiser_group.rb deleted file mode 100755 index f6543c5..0000000 --- a/ruby/v3.5/advertisers/assign_advertiser_to_advertiser_group.rb +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example assigns an advertiser to an advertiser group. -# -# CAUTION: An advertiser that has campaigns associated with it cannot be -# removed from an advertiser group once assigned. - -require_relative '../dfareporting_utils' - -def assign_advertiser_to_advertiser_group(profile_id, advertiser_id, - advertiser_group_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a the advertiser group association to patch. - advertiser = DfareportingUtils::API_NAMESPACE::Advertiser.new( - advertiser_group_id: advertiser_group_id - ) - - # Patch the advertiser group association. - result = service.patch_advertiser(profile_id, advertiser_id, advertiser) - - # Display results - puts format('Assigned advertiser with ID %d to advertiser group with ID %d.', - result.id, result.advertiser_group_id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :advertiser_group_id) - - assign_advertiser_to_advertiser_group(args[:profile_id], - args[:advertiser_id], args[:advertiser_group_id]) -end diff --git a/ruby/v3.5/advertisers/create_advertiser.rb b/ruby/v3.5/advertisers/create_advertiser.rb deleted file mode 100755 index 0e1eb29..0000000 --- a/ruby/v3.5/advertisers/create_advertiser.rb +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an advertiser in a given DCM account. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_advertiser(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new advertiser resource to insert. - advertiser = DfareportingUtils::API_NAMESPACE::Advertiser.new( - name: format('Example Advertiser #%s', SecureRandom.hex(3)), - status: 'APPROVED' - ) - - # Insert the advertiser. - result = service.insert_advertiser(profile_id, advertiser) - - # Display results. - puts format('Created advertiser with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_advertiser(args[:profile_id]) -end diff --git a/ruby/v3.5/advertisers/create_advertiser_group.rb b/ruby/v3.5/advertisers/create_advertiser_group.rb deleted file mode 100755 index a74ea38..0000000 --- a/ruby/v3.5/advertisers/create_advertiser_group.rb +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an advertiser group. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_advertiser_group(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new advertiser group resource to insert. - advertiser_group = DfareportingUtils::API_NAMESPACE::AdvertiserGroup.new( - name: format('Example Advertiser Group #%s', SecureRandom.hex(3)) - ) - - # Insert the advertiser group. - result = service.insert_advertiser_group(profile_id, advertiser_group) - - # Display results. - puts format('Created advertiser group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_advertiser_group(args[:profile_id]) -end diff --git a/ruby/v3.5/advertisers/create_advertiser_landing_page.rb b/ruby/v3.5/advertisers/create_advertiser_landing_page.rb deleted file mode 100755 index 809eda5..0000000 --- a/ruby/v3.5/advertisers/create_advertiser_landing_page.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an advertiser landing page. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_advertiser_landing_page(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new landing page resource to insert. - landing_page = DfareportingUtils::API_NAMESPACE::LandingPage.new( - advertiser_id: advertiser_id, - archived: false, - name: format('Example Advertiser Landing Page #%s', SecureRandom.hex(3)), - url: 'https://www.google.com' - ) - - # Insert the advertiser landing page. - result = service.insert_advertiser_landing_page(profile_id, landing_page) - - # Display results. - puts format('Created advertiser landing page with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_advertiser_landing_page(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/advertisers/get_advertiser_groups.rb b/ruby/v3.5/advertisers/get_advertiser_groups.rb deleted file mode 100755 index a4fe958..0000000 --- a/ruby/v3.5/advertisers/get_advertiser_groups.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all advertiser groups for the specified user profile. - -require_relative '../dfareporting_utils' - -def get_advertiser_groups(profile_id) - # Authenticate and initialize API service - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_advertiser_groups(profile_id, - page_token: token, - fields: 'nextPageToken,advertiserGroups(id,name)') - - # Display results. - if result.advertiser_groups.any? - result.advertiser_groups.each do |group| - puts format('Found advertiser group with ID %d and name "%s".', - group.id, group.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_advertiser_groups(args[:profile_id]) -end diff --git a/ruby/v3.5/advertisers/get_advertiser_landing_pages.rb b/ruby/v3.5/advertisers/get_advertiser_landing_pages.rb deleted file mode 100755 index 2db2713..0000000 --- a/ruby/v3.5/advertisers/get_advertiser_landing_pages.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all advertiser landing pages for the specified user -# profile. - -require_relative '../dfareporting_utils' - -def get_advertiser_landing_pages(profile_id, advertiser_id) - # Authenticate and initialize API service - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_advertiser_landing_pages(profile_id, - advertiser_ids: [advertiser_id], - page_token: token, - fields: 'nextPageToken,landingPages(id,name)') - - # Display results. - if result.landing_pages.any? - result.landing_pages.each do |landing_page| - puts format('Found advertiser landing page with ID %d and name "%s".', - landing_page.id, landing_page.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_advertiser_landing_pages(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/advertisers/get_advertisers.rb b/ruby/v3.5/advertisers/get_advertisers.rb deleted file mode 100755 index 9f97fb8..0000000 --- a/ruby/v3.5/advertisers/get_advertisers.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all advertisers. - -require_relative '../dfareporting_utils' - -def get_advertisers(profile_id) - # Authenticate and initialize API service - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_advertisers(profile_id, - page_token: token, - fields: 'nextPageToken,advertisers(id,name)') - - # Display results. - if result.advertisers.any? - result.advertisers.each do |advertiser| - puts format('Found advertiser with ID %d and name "%s".', - advertiser.id, advertiser.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_advertisers(args[:profile_id]) -end diff --git a/ruby/v3.5/auth/authenticate_using_service_account.rb b/ruby/v3.5/auth/authenticate_using_service_account.rb deleted file mode 100755 index 6fc63d4..0000000 --- a/ruby/v3.5/auth/authenticate_using_service_account.rb +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example demonstrates how to authenticate using a service account. -# -# An optional Google account email to impersonate may be specified as follows: -# authenticate_using_service_account.rb --i -# -# This optional flag only applies to service accounts which have domain-wide -# delegation enabled and wish to make API requests on behalf of an account -# within that domain. Using this flag will not allow you to impersonate a -# user from a domain you don't own (e.g., gmail.com). - -require 'google/apis/dfareporting_v3_5' -require 'googleauth' -require 'optparse' - -API_NAMESPACE = Google::Apis::DfareportingV3_5 - -def authenticate_using_service_account(path_to_json_file, impersonation_email) - # Create a Dfareporting service object. - # - # Note: application name should be replaced with a value that identifies - # your application. Suggested format is "MyCompany-ProductName". - service = API_NAMESPACE::DfareportingService.new - service.client_options.application_name = 'Ruby service account sample' - service.client_options.application_version = '1.0.0' - - # Generate an authorization object from the specified JSON file. - File.open(path_to_json_file, 'r+') do |json| - service.authorization = - Google::Auth::ServiceAccountCredentials.make_creds( - json_key_io: json, - scope: [API_NAMESPACE::AUTH_DFAREPORTING] - ) - end - - # Configure impersonation (if applicable). - service.authorization.sub = impersonation_email unless - impersonation_email.nil? - - service -end - -def get_userprofiles(service) - # Get all user profiles. - result = service.list_user_profiles - - # Display results. - result.items.each do |profile| - puts format( - 'User profile with ID %d and name "%s" was found for account %d.', - profile.profile_id, profile.user_name, profile.account_id - ) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - impersonation_email = nil - optparse = OptionParser.new do |opts| - opts.banner = format('Usage: %s path_to_json_file [options]', $PROGRAM_NAME) - opts.on_tail('-i', '--impersonate EMAIL', - 'Google account email to impersonate') do |email| - impersonation_email = email - end - end - optparse.parse! - - if ARGV.empty? - puts optparse - exit(-1) - end - - # Authenticate and initialize API service using service account. - service = authenticate_using_service_account(ARGV.shift, impersonation_email) - - get_userprofiles(service) -end diff --git a/ruby/v3.5/auth/authenticate_using_user_account.rb b/ruby/v3.5/auth/authenticate_using_user_account.rb deleted file mode 100755 index 9ce6a29..0000000 --- a/ruby/v3.5/auth/authenticate_using_user_account.rb +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example demonstrates how to authenticate using a user account, via the -# OAuth 2.0 installed application flow. - -require 'google/apis/dfareporting_v3_5' -require 'googleauth' -require 'googleauth/stores/file_token_store' - -API_NAMESPACE = Google::Apis::DfareportingV3_5 - -# This redirect URI allows you to copy the token from the success screen. -OAUTH_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze - -# Location where authorization credentials will be cached. -TOKEN_STORE_DIR = File.join(File.dirname(__FILE__), 'auth-sample.yaml') - -def authenticate_using_user_account(path_to_json_file, token_store) - # Load client ID from the specified file. - client_id = Google::Auth::ClientId.from_file(path_to_json_file) - - # Set up the user authorizer. - # - # Note: providing a token store allows auth credentials to be cached, so they - # survive multiple runs of the application. This avoids prompting the user for - # authorization every time the access token expires, by remembering the - # refresh token. - authorizer = Google::Auth::UserAuthorizer.new( - client_id, [API_NAMESPACE::AUTH_DFAREPORTING], token_store - ) - - # Authorize and persist credentials to the data store. - # - # Note: the 'user' value below is used to identify a specific set of - # credentials in the token store. You may provide different values here to - # persist credentials for multiple users to the same token store. - authorization = authorizer.get_credentials('user') - if authorization.nil? - puts format( - "Open this URL in your browser and authorize the application.\n\n%s" \ - "\n\nEnter the authorization code:", - authorizer.get_authorization_url(base_url: OAUTH_REDIRECT_URI) - ) - code = STDIN.gets.chomp - authorization = authorizer.get_and_store_credentials_from_code( - base_url: OAUTH_REDIRECT_URI, code: code, user_id: 'user' - ) - end - - authorization -end - -def create_dfareporting_service_instance(authorization) - # Create a Dfareporting service object. - # - # Note: application name should be replaced with a value that identifies - # your application. Suggested format is "MyCompany-ProductName". - service = API_NAMESPACE::DfareportingService.new - service.authorization = authorization - service.client_options.application_name = 'Ruby installed app sample' - service.client_options.application_version = '1.0.0' - - service -end - -def get_userprofiles(service) - # Get all user profiles. - result = service.list_user_profiles - - # Display results. - result.items.each do |profile| - puts format( - 'User profile with ID %d and name "%s" was found for account %d.', - profile.profile_id, profile.user_name, profile.account_id - ) - end -end - -if $PROGRAM_NAME == __FILE__ - if ARGV.empty? - puts format('Usage: %s path_to_json_file', $PROGRAM_NAME) - exit(-1) - end - - # Authenticate using user account. - authorization = authenticate_using_user_account( - ARGV.shift, - Google::Auth::Stores::FileTokenStore.new(file: TOKEN_STORE_DIR) - ) - - # Initialize API service, - service = create_dfareporting_service_instance(authorization) - - get_userprofiles(service) -end diff --git a/ruby/v3.5/campaigns/create_campaign.rb b/ruby/v3.5/campaigns/create_campaign.rb deleted file mode 100755 index 4feceb4..0000000 --- a/ruby/v3.5/campaigns/create_campaign.rb +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a campaign in a given advertiser. -# -# To create an advertiser, run create_advertiser.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_campaign(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Create a new campaign resource to insert. - campaign = DfareportingUtils::API_NAMESPACE::Campaign.new( - advertiser_id: advertiser_id, - archived: false, - default_landing_page_id: default_landing_page.id, - name: format('Example Campaign #%s', SecureRandom.hex(3)), - start_date: '2014-01-01', - end_date: '2020-01-01' - ) - - # Insert the campaign. - result = service.insert_campaign(profile_id, campaign) - - # Display results. - puts format('Created campaign with ID %d and name "%s".', result.id, - result.name) -end - -def get_advertiser_landing_page(service, profile_id, advertiser_id) - # Retrieve a sigle landing page from the specified advertiser. - result = service.list_advertiser_landing_pages(profile_id, - advertiser_ids: [advertiser_id], - max_results: 1) - - if result.landing_pages.none? - abort format('No landing pages for for advertiser with ID %d', - advertiser_id) - end - - result.landing_pages[0] -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_campaign(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/campaigns/create_campaign_event_tag.rb b/ruby/v3.5/campaigns/create_campaign_event_tag.rb deleted file mode 100755 index 18d221e..0000000 --- a/ruby/v3.5/campaigns/create_campaign_event_tag.rb +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative field associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_campaign_event_tag(profile_id, campaign_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new event tag resource to insert. - event_tag = DfareportingUtils::API_NAMESPACE::EventTag.new( - campaign_id: campaign_id, - name: format('Example Campaign Event Tag #%s', SecureRandom.hex(3)), - status: 'ENABLED', - type: 'CLICK_THROUGH_EVENT_TAG', - url: 'https://www.google.com' - ) - - # Insert the event tag. - result = service.insert_event_tag(profile_id, event_tag) - - # Display results. - puts format('Created campaign event tag with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id) - - create_campaign_event_tag(args[:profile_id], args[:campaign_id]) -end diff --git a/ruby/v3.5/campaigns/get_campaigns.rb b/ruby/v3.5/campaigns/get_campaigns.rb deleted file mode 100755 index 81fa930..0000000 --- a/ruby/v3.5/campaigns/get_campaigns.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all existing campaigns for the specified user profile. - -require_relative '../dfareporting_utils' - -def get_campaigns(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_campaigns(profile_id, - page_token: token, - fields: 'nextPageToken,campaigns(id,name)') - - # Display results. - if result.campaigns.any? - result.campaigns.each do |campaign| - puts format('Found campaign with ID %d and name "%s".', campaign.id, - campaign.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_campaigns(args[:profile_id]) -end diff --git a/ruby/v3.5/conversions/insert_offline_mobile_conversion.rb b/ruby/v3.5/conversions/insert_offline_mobile_conversion.rb deleted file mode 100755 index 5cbafdb..0000000 --- a/ruby/v3.5/conversions/insert_offline_mobile_conversion.rb +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example inserts an offline conversion attributed to a mobile device ID. - -require_relative '../dfareporting_utils' -require 'date' - -def insert_offline_mobile_conversion(profile_id, mobile_device_id, - floodlight_activity_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - floodlight_activity_id) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - current_time_in_micros = DateTime.now.strftime('%Q').to_i * 1000 - - # Construct the conversion. - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - floodlight_activity_id: floodlight_activity_id, - floodlight_configuration_id: floodlight_config_id, - ordinal: current_time_in_micros, - mobile_device_id: mobile_device_id, - timestamp_micros: current_time_in_micros - ) - - # Construct the batch insert request. - batch_insert_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchInsertRequest.new( - conversions: [conversion] - ) - - # Insert the conversion. - result = service.batchinsert_conversion(profile_id, batch_insert_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) inserting conversion for mobile device ID %s.', - mobile_device_id) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully inserted conversion for mobile device ID %s.', - mobile_device_id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :mobile_device_id, - :floodlight_activity_id) - - insert_offline_mobile_conversion(args[:profile_id], args[:mobile_device_id], - args[:floodlight_activity_id]) -end diff --git a/ruby/v3.5/conversions/insert_offline_user_conversion.rb b/ruby/v3.5/conversions/insert_offline_user_conversion.rb deleted file mode 100755 index 7f03ea9..0000000 --- a/ruby/v3.5/conversions/insert_offline_user_conversion.rb +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example inserts an offline conversion attributed to an encrypted user -# ID. - -require_relative '../dfareporting_utils' -require 'date' - -# Inserts an offline user conversions with the specified values. -# -# @param profile_id [Number] The ID of the DCM user issuing this request. -# @param encrypted_user_id [String] The encrypted user ID to which the -# conversion should be attributed. -# @param floodlight_activity_id [Number] The Floodlight activity ID to which -# the conversion should be attributed. -# @param encryption [Object] A hash containing the values used to encrypt the -# specified user ID. The expected format is: -# { -# source: , -# entity_id: , -# entity_type: -# } -def insert_offline_user_conversion(profile_id, encrypted_user_id, - floodlight_activity_id, encryption = {}) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - floodlight_activity_id) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - current_time_in_micros = DateTime.now.strftime('%Q').to_i * 1000 - - # Construct the conversion. - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - encrypted_user_id: encrypted_user_id, - floodlight_activity_id: floodlight_activity_id, - floodlight_configuration_id: floodlight_config_id, - ordinal: current_time_in_micros, - timestamp_micros: current_time_in_micros - ) - - # Construct the encryption info. - encryption_info = DfareportingUtils::API_NAMESPACE::EncryptionInfo.new( - encryption_entity_id: encryption[:entity_id], - encryption_entity_type: encryption[:entity_type], - encryption_source: encryption[:source] - ) - - # Construct the batch insert request. - batch_insert_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchInsertRequest.new( - conversions: [conversion], - encryption_info: encryption_info - ) - - # Insert the conversion. - result = service.batchinsert_conversion(profile_id, batch_insert_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) inserting conversion for encrypted user ID %s.', - encrypted_user_id) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully inserted conversion for encrypted user ID %s.', - encrypted_user_id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :encrypted_user_id, :encryption_source, :encryption_entity_id, - :encryption_entity_type, :floodlight_activity_id) - - insert_offline_user_conversion(args[:profile_id], args[:encrypted_user_id], - args[:floodlight_activity_id], - source: args[:encryption_source], - entity_id: args[:encryption_entity_id], - entity_type: args[:encryption_entity_type]) -end diff --git a/ruby/v3.5/conversions/update_offline_mobile_conversion.rb b/ruby/v3.5/conversions/update_offline_mobile_conversion.rb deleted file mode 100755 index 6e1cb75..0000000 --- a/ruby/v3.5/conversions/update_offline_mobile_conversion.rb +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example updates an offline conversion attributed to a mobile device ID. -# -# To create a conversion attributed to a mobile device ID, run -# insert_offline_mobile_conversion.rb. - -require_relative '../dfareporting_utils' - -# Updates an offline mobile conversion with the specified values. -# -# @param profile_id [Number] The ID of the DCM user issuing this request. -# @param new_quantity [Number] The new quantity value to assign to the -# specified conversion. -# @param new_value [Number] The new value to assign to the specified -# conversion. -# @param existing_conversion [Object] A hash containing values that identify -# an existing offline mobile conversion. The expected format is: -# { -# mobile_device_id: , -# floodlight_activity_id: , -# ordinal: , -# timestamp: -# } -def update_offline_mobile_conversion(profile_id, new_quantity, new_value, - existing_conversion = {}) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - existing_conversion[:floodlight_activity_id]) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - # Construct the conversion with values that identify the conversion to - # update - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - floodlight_activity_id: existing_conversion[:floodlight_activity_id], - floodlight_configuration_id: floodlight_config_id, - ordinal: existing_conversion[:ordinal], - mobile_device_id: existing_conversion[:mobile_device_id], - timestamp_micros: existing_conversion[:timestamp] - ) - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion.quantity = new_quantity - conversion.value = new_value - - # Construct the batch update request. - batch_update_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchUpdateRequest.new( - conversions: [conversion] - ) - - # Update the conversion. - result = service.batchupdate_conversion(profile_id, batch_update_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) updating conversion for mobile device ID %s.', - existing_conversion[:mobile_device_id]) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully updated conversion for mobile device ID %s.', - existing_conversion[:mobile_device_id]) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :mobile_device_id, - :floodlight_activity_id, :ordinal, :timestamp, :new_quantity, :new_value) - - update_offline_mobile_conversion( - args[:profile_id], args[:new_quantity], args[:new_value], - mobile_device_id: args[:mobile_device_id], - floodlight_activity_id: args[:floodlight_activity_id], - ordinal: args[:ordinal], - timestamp: args[:timestamp] - ) -end diff --git a/ruby/v3.5/conversions/update_offline_user_conversion.rb b/ruby/v3.5/conversions/update_offline_user_conversion.rb deleted file mode 100755 index c851938..0000000 --- a/ruby/v3.5/conversions/update_offline_user_conversion.rb +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example updates an offline conversion attributed to an encrypted user -# ID. -# -# To create a conversion attributed to an encrypted user ID, run -# insert_offline_user_conversion.rb. - -require_relative '../dfareporting_utils' - -# Updates an offline user conversion with the specified values. -# -# @param profile_id [Number] The ID of the DCM user issuing this request. -# @param new_quantity [Number] The new quantity value to assign to the -# specified conversion. -# @param new_value [Number] The new value to assign to the specified -# conversion. -# @param existing_conversion [Object] A hash containing values that identify -# an existing offline user conversion. The expected format is: -# { -# encrypted_user_id: , -# floodlight_activity_id: , -# ordinal: , -# timestamp: -# } -# @param encryption [Object] A hash containing the values used to encrypt the -# existing user conversion. The expected format is: -# { -# source: , -# entity_id: , -# entity_type: -# } -def update_offline_user_conversion(profile_id, new_quantity, new_value, - existing_conversion = {}, encryption = {}) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the Floodlight configuration ID based on activity ID. - floodlight_activity = service.get_floodlight_activity(profile_id, - existing_conversion[:floodlight_activity_id]) - floodlight_config_id = floodlight_activity.floodlight_configuration_id - - # Construct the conversion with values that identify the conversion to - # update. - conversion = DfareportingUtils::API_NAMESPACE::Conversion.new( - encrypted_user_id: existing_conversion[:encrypted_user_id], - floodlight_activity_id: existing_conversion[:floodlight_activity_id], - floodlight_configuration_id: floodlight_config_id, - ordinal: existing_conversion[:ordinal], - timestamp_micros: existing_conversion[:timestamp] - ) - - # Set the fields to be updated. These fields are required; to preserve a - # value from the existing conversion, it must be copied over manually. - conversion.quantity = new_quantity - conversion.value = new_value - - # Construct the encryption info. - encryption_info = DfareportingUtils::API_NAMESPACE::EncryptionInfo.new( - encryption_entity_id: encryption[:entity_id], - encryption_entity_type: encryption[:entity_type], - encryption_source: encryption[:source] - ) - - # Construct the batch update request. - batch_update_request = - DfareportingUtils::API_NAMESPACE::ConversionsBatchUpdateRequest.new( - conversions: [conversion], - encryption_info: encryption_info - ) - - # Update the conversion. - result = service.batchupdate_conversion(profile_id, batch_update_request) - - process_response(result) -end - -def process_response(result) - if result.has_failures - puts format('Error(s) updating conversion for encrypted user ID %s.', - existing_conversion[:encrypted_user_id]) - - status = result.status[0] - status.errors.each do |error| - puts format("\t[%s]: %s", error.code, error.message) - end - else - puts format('Successfully updated conversion for encrypted user ID %s.', - existing_conversion[:encrypted_user_id]) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :encrypted_user_id, :encryption_source, :encryption_entity_id, - :encryption_entity_type, :floodlight_activity_id, :ordinal, :timestamp, - :new_quantity, :new_value) - - update_offline_user_conversion( - args[:profile_id], args[:new_quantity], args[:new_value], - { - encrypted_user_id: args[:encrypted_user_id], - floodlight_activity_id: args[:floodlight_activity_id], - ordinal: args[:ordinal], - timestamp: args[:timestamp] - }, - source: args[:encryption_source], - entity_id: args[:encryption_entity_id], - entity_type: args[:encryption_entity_type] - ) -end diff --git a/ruby/v3.5/creative_asset_utils.rb b/ruby/v3.5/creative_asset_utils.rb deleted file mode 100755 index d4d112a..0000000 --- a/ruby/v3.5/creative_asset_utils.rb +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Utility class for handling common tasks related to working with creative -# assets. - -require_relative 'dfareporting_utils' - -# Creative asset utilities used by DFA Reporting and Trafficking API creative -# examples. -class CreativeAssetUtils - # Creates a new instance of CreativeAssetUtils. - def initialize(service, profile_id) - @service = service - @profile_id = profile_id - end - - # Uploads a creative asset and returns the creative asset metadata. - def upload_asset(advertiser_id, path_to_asset_file, asset_type) - asset_name = File.basename(path_to_asset_file) - - # Construct the creative asset metadata - creative_asset = DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: DfareportingUtils::API_NAMESPACE::CreativeAssetId.new( - name: asset_name, - type: asset_type - ) - ) - - # Upload the asset. - mime_type = determine_mime_type(path_to_asset_file, asset_type) - - result = @service.insert_creative_asset( - @profile_id, - advertiser_id, - creative_asset, - content_type: mime_type, - upload_source: path_to_asset_file - ) - - puts format('Creative asset was saved with name "%s".', - result.asset_identifier.name) - - result - end - - # Performs a naive mime-type lookup based on file name and asset type. - def determine_mime_type(path_to_asset_file, asset_type) - case asset_type - when 'IMAGE', 'HTML_IMAGE' - return format('image/%s', File.extname(path_to_asset_file)) - when 'VIDEO' - format('video/%s', File.extname(path_to_asset_file)) - else - 'application/octet-stream' - end - end -end diff --git a/ruby/v3.5/creatives/assign_creative_to_campaign.rb b/ruby/v3.5/creatives/assign_creative_to_campaign.rb deleted file mode 100755 index 142ad79..0000000 --- a/ruby/v3.5/creatives/assign_creative_to_campaign.rb +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example assigns a given creative to a given campaign. -# -# Note that both the creative and campaign must be associated with the same -# advertiser. - -require_relative '../dfareporting_utils' - -def assign_creative_to_campaign(profile_id, campaign_id, creative_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative-campaign association to insert - association = - DfareportingUtils::API_NAMESPACE::CampaignCreativeAssociation.new( - creative_id: creative_id - ) - - # Insert the advertiser group. - result = service.insert_campaign_creative_association(profile_id, campaign_id, - association) - - # Display results. - puts format('Creative with ID %d is now associated with campaign %d.', - result.creative_id, campaign_id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :creative_id) - - assign_creative_to_campaign(args[:profile_id], args[:campaign_id], - args[:creative_id]) -end diff --git a/ruby/v3.5/creatives/create_creative_field.rb b/ruby/v3.5/creatives/create_creative_field.rb deleted file mode 100755 index dd1e7d9..0000000 --- a/ruby/v3.5/creatives/create_creative_field.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative field associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_creative_field(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative field resource to insert, - creative_field = DfareportingUtils::API_NAMESPACE::CreativeField.new( - advertiser_id: advertiser_id, - name: format('Example Creative Field #%s', SecureRandom.hex(3)) - ) - - # Insert the creative field, - result = service.insert_creative_field(profile_id, creative_field) - - # Display results, - puts format('Created creative field with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments, - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_creative_field(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/creatives/create_creative_field_value.rb b/ruby/v3.5/creatives/create_creative_field_value.rb deleted file mode 100755 index 8daf06a..0000000 --- a/ruby/v3.5/creatives/create_creative_field_value.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative field value for a given creative field. -# -# To get the creative field ID, run get_creative_fields.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_creative_field_value(profile_id, field_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative field value resource to insert. - field_value = DfareportingUtils::API_NAMESPACE::CreativeFieldValue.new( - value: format('Example Creative Field Value #%s', SecureRandom.hex(3)) - ) - - # Insert the creative field value. - result = service.insert_creative_field_value(profile_id, field_id, - field_value) - - # Display results. - puts format('Created creative field value with ID %d and value "%s".', - result.id, result.value) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :field_id) - - create_creative_field_value(args[:profile_id], args[:field_id]) -end diff --git a/ruby/v3.5/creatives/create_creative_group.rb b/ruby/v3.5/creatives/create_creative_group.rb deleted file mode 100755 index 41f3054..0000000 --- a/ruby/v3.5/creatives/create_creative_group.rb +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a creative group associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. Valid group numbers are -# limited to 1 or 2. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_creative_group(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative group resource to insert. - creative_group = DfareportingUtils::API_NAMESPACE::CreativeGroup.new( - advertiser_id: advertiser_id, - group_number: 1, - name: format('Example Creative Group #%s', SecureRandom.hex(3)) - ) - - # Insert the creative group. - result = service.insert_creative_group(profile_id, creative_group) - - # Display results. - puts format('Created creative group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_creative_group(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/creatives/create_display_image_gallery_creative.rb b/ruby/v3.5/creatives/create_display_image_gallery_creative.rb deleted file mode 100755 index 720d37f..0000000 --- a/ruby/v3.5/creatives/create_display_image_gallery_creative.rb +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a display image gallery creative. -# -# Requires two image assets and an advertiser ID as input. To get an advertiser -# ID, run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_enhanced_image_creative(profile_id, advertiser_id, size_id, - path_to_image1_file, path_to_image2_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - util = CreativeAssetUtils.new(service, profile_id) - - # Upload the first image asset. - image1_asset_id = util.upload_asset(advertiser_id, path_to_image1_file, - 'HTML_IMAGE').asset_identifier - - # Upload the second image asset. - image2_asset_id = util.upload_asset(advertiser_id, path_to_image2_file, - 'HTML_IMAGE').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - auto_advance_images: true, - click_tags: [ - DfareportingUtils::API_NAMESPACE::ClickTag.new( - event_name: image1_asset_id.name, - name: image1_asset_id.name - ), - DfareportingUtils::API_NAMESPACE::ClickTag.new( - event_name: image2_asset_id.name, - name: image2_asset_id.name - ) - ], - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: image1_asset_id, - role: 'PRIMARY' - ), - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: image2_asset_id, - role: 'PRIMARY' - ) - ], - name: 'Example display image gallery creative', - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY_IMAGE_GALLERY' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format( - 'Created display image gallery creative with ID %d and name "%s".', - result.id, result.name - ) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :size_id, :path_to_image1_file, :path_to_image2_file) - - create_enhanced_image_creative(args[:profile_id], args[:advertiser_id], - args[:size_id], args[:path_to_image1_file], args[:path_to_image2_file]) -end diff --git a/ruby/v3.5/creatives/create_display_redirect_creative.rb b/ruby/v3.5/creatives/create_display_redirect_creative.rb deleted file mode 100755 index 68ed09d..0000000 --- a/ruby/v3.5/creatives/create_display_redirect_creative.rb +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a display redirect creative associated with a given -# advertiser. -# -# To get a size ID, run get_size.rb. - -require_relative '../dfareporting_utils' - -def create_tracking_creative(profile_id, advertiser_id, image_url, size_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative resource to insert. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - name: 'Example display redirect creative', - redirect_url: image_url, - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY_REDIRECT' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - # Display results. - puts format('Created display redirect creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :image_url, :size_id) - - create_tracking_creative(args[:profile_id], args[:advertiser_id], - args[:image_url], args[:size_id]) -end diff --git a/ruby/v3.5/creatives/create_html5_display_creative.rb b/ruby/v3.5/creatives/create_html5_display_creative.rb deleted file mode 100755 index 62abc6c..0000000 --- a/ruby/v3.5/creatives/create_html5_display_creative.rb +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an HTML5 display creative. -# -# Requires an HTML5 asset, backup image asset, and an advertiser ID as input. -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_html5_banner_creative(profile_id, advertiser_id, size_id, - path_to_html5_asset_file, path_to_backup_image_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - util = CreativeAssetUtils.new(service, profile_id) - - # Locate an advertiser landing page to use as a default. - default_landing_page = get_advertiser_landing_page(service, profile_id, - advertiser_id) - - # Upload the HTML5 asset. - html5_asset_id = util.upload_asset(advertiser_id, path_to_html5_asset_file, - 'HTML').asset_identifier - - # Upload the backup image asset. - backup_image_asset_id = util.upload_asset(advertiser_id, - path_to_backup_image_file, 'HTML_IMAGE').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - backup_image_click_through_url: - DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new( - landing_page_id: default_landing_page.id - ), - backup_image_reporting_label: 'backup', - backup_image_target_window: - DfareportingUtils::API_NAMESPACE::TargetWindow.new( - target_window_option: 'NEW_WINDOW' - ), - click_tags: [ - DfareportingUtils::API_NAMESPACE::ClickTag.new( - event_name: 'exit', - name: 'click_tag', - click_through_url: - DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new( - landing_page_id: default_landing_page.id - ) - ) - ], - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: html5_asset_id, - role: 'PRIMARY' - ), - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: backup_image_asset_id, - role: 'BACKUP_IMAGE' - ) - ], - name: 'Example HTML5 display creative', - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created HTML5 display creative with ID %d and name "%s".', - result.id, result.name) -end - -def get_advertiser_landing_page(service, profile_id, advertiser_id) - # Retrieve a sigle landing page from the specified advertiser. - result = service.list_advertiser_landing_pages(profile_id, - advertiser_ids: [advertiser_id], - max_results: 1) - - if result.landing_pages.none? - abort format('No landing pages for for advertiser with ID %d', - advertiser_id) - end - - result.landing_pages[0] -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :size_id, :path_to_html5_asset_file, :path_to_backup_image_file) - - create_html5_banner_creative(args[:profile_id], args[:advertiser_id], - args[:size_id], args[:path_to_html5_asset_file], - args[:path_to_backup_image_file]) -end diff --git a/ruby/v3.5/creatives/create_image_display_creative.rb b/ruby/v3.5/creatives/create_image_display_creative.rb deleted file mode 100755 index df81b14..0000000 --- a/ruby/v3.5/creatives/create_image_display_creative.rb +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an image display creative. -# -# Requires an image asset and advertiser ID as input. To get an advertiser ID, -# run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_image_display_creative(profile_id, advertiser_id, size_id, - path_to_image_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Upload the creative asset. - util = CreativeAssetUtils.new(service, profile_id) - creative_asset_id = util.upload_asset(advertiser_id, path_to_image_file, - 'HTML_IMAGE').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: creative_asset_id, - role: 'PRIMARY' - ) - ], - name: 'Example image display creative', - size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), - type: 'DISPLAY' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created image display creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :size_id, :path_to_image_file) - - create_image_display_creative(args[:profile_id], args[:advertiser_id], - args[:size_id], args[:path_to_image_file]) -end diff --git a/ruby/v3.5/creatives/create_instream_audio_creative.rb b/ruby/v3.5/creatives/create_instream_audio_creative.rb deleted file mode 100755 index ac2234d..0000000 --- a/ruby/v3.5/creatives/create_instream_audio_creative.rb +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2018, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an in-stream audio creative. -# -# Requires an audio asset and advertiser ID as input. To get an advertiser ID, -# run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_instream_audio_creative(profile_id, advertiser_id, - path_to_audio_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Upload the creative asset. - util = CreativeAssetUtils.new(service, profile_id) - creative_asset_id = util.upload_asset(advertiser_id, path_to_audio_file, - 'AUDIO').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: creative_asset_id, - role: 'PARENT_AUDIO' - ) - ], - name: 'Example in-stream audio creative', - type: 'INSTREAM_AUDIO' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created in-stream audio creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :path_to_audio_file) - - create_instream_audio_creative(args[:profile_id], args[:advertiser_id], - args[:path_to_audio_file]) -end diff --git a/ruby/v3.5/creatives/create_instream_video_creative.rb b/ruby/v3.5/creatives/create_instream_video_creative.rb deleted file mode 100755 index 027d15c..0000000 --- a/ruby/v3.5/creatives/create_instream_video_creative.rb +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an in-stream video creative. -# -# Requires a video asset and advertiser ID as input. To get an advertiser ID, -# run get_advertisers.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def create_instream_video_creative(profile_id, advertiser_id, - path_to_video_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Upload the creative asset. - util = CreativeAssetUtils.new(service, profile_id) - creative_asset_id = util.upload_asset(advertiser_id, path_to_video_file, - 'VIDEO').asset_identifier - - # Construct the creative structure. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - creative_assets: [ - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: creative_asset_id, - role: 'PARENT_VIDEO' - ) - ], - name: 'Example in-stream video creative', - type: 'INSTREAM_VIDEO' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - puts format('Created in-stream video creative with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :path_to_video_file) - - create_instream_video_creative(args[:profile_id], args[:advertiser_id], - args[:path_to_video_file]) -end diff --git a/ruby/v3.5/creatives/create_tracking_creative.rb b/ruby/v3.5/creatives/create_tracking_creative.rb deleted file mode 100755 index 302cb94..0000000 --- a/ruby/v3.5/creatives/create_tracking_creative.rb +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a tracking creative associated with a given advertiser. - -require_relative '../dfareporting_utils' - -def create_tracking_creative(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new creative resource to insert. - creative = DfareportingUtils::API_NAMESPACE::Creative.new( - advertiser_id: advertiser_id, - name: 'Example Tracking Creative', - type: 'TRACKING_TEXT' - ) - - # Insert the creative. - result = service.insert_creative(profile_id, creative) - - # Display results. - puts format('Created tracking creative with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_tracking_creative(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/creatives/get_creative_field_values.rb b/ruby/v3.5/creatives/get_creative_field_values.rb deleted file mode 100755 index 8703fbb..0000000 --- a/ruby/v3.5/creatives/get_creative_field_values.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all creative field values. - -require_relative '../dfareporting_utils' - -def get_creative_field_values(profile_id, field_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creative_field_values(profile_id, field_id, - page_token: token, - fields: 'nextPageToken,creativeFieldValues(id,value)') - - # Display results. - if result.creative_field_values.any? - result.creative_field_values.each do |value| - puts format('Found creative field value with ID %d and value "%s".', - value.id, value.value) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :field_id) - - get_creative_field_values(args[:profile_id], args[:field_id]) -end diff --git a/ruby/v3.5/creatives/get_creative_fields.rb b/ruby/v3.5/creatives/get_creative_fields.rb deleted file mode 100755 index 04028cd..0000000 --- a/ruby/v3.5/creatives/get_creative_fields.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all creative fields. - -require_relative '../dfareporting_utils' - -def get_creative_fields(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creative_fields(profile_id, - page_token: token, - fields: 'nextPageToken,creativeFields(id,name)') - - # Display results. - if result.creative_fields.any? - result.creative_fields.each do |field| - puts format('Found creative field with ID %d and name "%s".', field.id, - field.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_creative_fields(args[:profile_id]) -end diff --git a/ruby/v3.5/creatives/get_creative_groups.rb b/ruby/v3.5/creatives/get_creative_groups.rb deleted file mode 100755 index 518f8c5..0000000 --- a/ruby/v3.5/creatives/get_creative_groups.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all creative groups. - -require_relative '../dfareporting_utils' - -def get_creative_groups(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creative_groups(profile_id, - page_token: token, - fields: 'nextPageToken,creativeGroups(id,name)') - - # Display results. - if result.creative_groups.any? - result.creative_groups.each do |group| - puts format('Found creative group with ID %d and name "%s".', group.id, - group.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_creative_groups(args[:profile_id]) -end diff --git a/ruby/v3.5/creatives/get_creatives.rb b/ruby/v3.5/creatives/get_creatives.rb deleted file mode 100755 index 1350a7f..0000000 --- a/ruby/v3.5/creatives/get_creatives.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example lists all existing active creatives for a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' - -def get_creatives(profile_id, _advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_creatives(profile_id, - page_token: token, - fields: 'nextPageToken,creatives(id,name,type)') - - # Display results. - if result.creatives.any? - result.creatives.each do |creative| - puts format('Found %s creative with ID %d and name "%s".', - creative.type, creative.id, creative.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_creatives(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/dfareporting_utils.rb b/ruby/v3.5/dfareporting_utils.rb deleted file mode 100755 index 45af64f..0000000 --- a/ruby/v3.5/dfareporting_utils.rb +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Handles common tasks across all DFA Reporting API samples. - -require 'google/apis/dfareporting_v3_5' -require 'googleauth' -require 'googleauth/stores/file_token_store' - -# Utility methods used by all DFA Reporting and Trafficking API samples. -module DfareportingUtils - API_NAME = 'dfareporting'.freeze - API_NAMESPACE = Google::Apis::DfareportingV3_5 - API_SCOPES = [ - API_NAMESPACE::AUTH_DDMCONVERSIONS, - API_NAMESPACE::AUTH_DFAREPORTING, - API_NAMESPACE::AUTH_DFATRAFFICKING - ].freeze - - CLIENT_SECRETS_FILE = 'client_secrets.json'.freeze - CREDENTIAL_STORE_FILE = "#{API_NAME}-oauth2.yaml".freeze - CREDENTIAL_STORE_PATH = File.dirname(__FILE__) - - # This redirect URI allows you to copy the token from the success screen. - OAUTH_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze - - # Handles validating command line arguments and returning them as a Hash - def self.parse_arguments(argument_values, *argument_names) - validate_arguments(argument_values, *argument_names) - generate_argument_map(argument_values, *argument_names) - end - - # Validates the number of command line arguments matches what was expected - def self.validate_arguments(argument_values, *argument_names) - return if argument_values.length == argument_names.length - - # Format the arguments for display (ie, '') - formatted_arguments = argument_names.map { |a| '<' + a.to_s + '>' } - - # Display a message to the user and exit - puts format('Usage: %s %s', $PROGRAM_NAME, formatted_arguments.join(' ')) - exit - end - private_class_method :validate_arguments - - # Converts parallel arrays of argument names and values into a single map - def self.generate_argument_map(argument_values, *argument_names) - ret = {} - argument_names.each_with_index do |arg, index| - ret[arg] = argument_values[index] - end - ret - end - private_class_method :generate_argument_map - - # Handles authentication and loading of the API. - def self.initialize_service - # Uncomment the following lines to enable logging. - # log_file = File.open("#{$0}.log", 'a+') - # log_file.sync = true - # logger = Logger.new(log_file) - # logger.level = Logger::DEBUG - # Google::Apis.logger = logger # Logging is set globally - - # Create an API Service object. - service = create_service_object - - # Load application default credentials if they're available. - authorization = authorize_application_default_credentials - - # Otherwise, load credentials from the provided client secrets file. - authorization = authorize_installed_application if authorization.nil? - - # If no credentials could be loaded, return an error. - if authorization.nil? - puts 'Could not load credentials. Enter client ID and secret from ' \ - 'https://console.developers.google.com/ into client_secrets.json.' - exit - end - - service.authorization = authorization - service - end - - # Returns an instance of the Dfareporting service without authentication. - def self.create_service_object - service = API_NAMESPACE::DfareportingService.new - service.client_options.application_name = "Ruby #{API_NAME} samples" - service.client_options.application_version = '1.0.0' - - service - end - private_class_method :create_service_object - - # Attempts to load application default credentials and return an - # authorization object that can be used to make requests. - def self.authorize_application_default_credentials - Google::Auth.get_application_default(API_SCOPES) - rescue StandardError - # No application default credentials, continue to try other options. - nil - end - private_class_method :authorize_application_default_credentials - - # Handles authorizing a user via the OAuth installed application flow and - # returns an authorization object that can be used to make requests. - def self.authorize_installed_application - # Load the client secrets. - client_id = load_client_secrets - return nil if client_id.nil? - - # FileTokenStore stores auth credentials in a file, so they survive - # multiple runs of the application. This avoids prompting the user for - # authorization every time the access token expires, by remembering the - # refresh token. - # - # Note: FileTokenStore is not suitable for multi-user applications. - token_store = Google::Auth::Stores::FileTokenStore.new( - file: File.join(CREDENTIAL_STORE_PATH, CREDENTIAL_STORE_FILE) - ) - - authorizer = Google::Auth::UserAuthorizer.new(client_id, API_SCOPES, - token_store) - - authorization = authorizer.get_credentials('default') - if authorization.nil? - puts format( - "Open this URL in your browser and authorize the application.\n\n%s" \ - "\n\nEnter the authorization code:", - authorizer.get_authorization_url(base_url: OAUTH_REDIRECT_URI) - ) - code = STDIN.gets.chomp - authorization = authorizer.get_and_store_credentials_from_code( - base_url: OAUTH_REDIRECT_URI, code: code, user_id: 'default' - ) - end - - authorization - end - private_class_method :authorize_installed_application - - def self.load_client_secrets - # Load client ID from the specified file. - client_id = Google::Auth::ClientId.from_file( - File.join(CREDENTIAL_STORE_PATH, CLIENT_SECRETS_FILE) - ) - - if client_id.id.start_with?('[[INSERT') || - client_id.secret.start_with?('[[INSERT') - return nil - end - - client_id - rescue StandardError - # Unable to load client_secrets.json. - nil - end - private_class_method :load_client_secrets -end diff --git a/ruby/v3.5/floodlight/create_floodlight_activity.rb b/ruby/v3.5/floodlight/create_floodlight_activity.rb deleted file mode 100755 index 3c200b3..0000000 --- a/ruby/v3.5/floodlight/create_floodlight_activity.rb +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a floodlight activity in a given activity group. -# -# To create an activity group, run create_floodlight_activity_group.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_floodlight_activity(profile_id, activity_group_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new floodlight activity resource to insert. - activity = DfareportingUtils::API_NAMESPACE::FloodlightActivity.new( - counting_method: 'STANDARD_COUNTING', - expected_url: 'http://www.google.com', - floodlight_activity_group_id: activity_group_id, - floodlight_tag_type: 'GLOBAL_SITE_TAG', - name: format('Example Floodlight Activity #%s', SecureRandom.hex(3)) - ) - - # Insert the floodlight activity. - result = service.insert_floodlight_activity(profile_id, activity) - - # Display results. - puts format('Created floodlight activity with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :activity_group_id) - - create_floodlight_activity(args[:profile_id], args[:activity_group_id]) -end diff --git a/ruby/v3.5/floodlight/create_floodlight_activity_group.rb b/ruby/v3.5/floodlight/create_floodlight_activity_group.rb deleted file mode 100755 index 33d1c81..0000000 --- a/ruby/v3.5/floodlight/create_floodlight_activity_group.rb +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a new activity group for a floodlight configuration. -# -# To get a floodlight configuration ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_floodlight_activity_group(profile_id, floodlight_config_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new floodlight activity group resource to insert. - activity_group = - DfareportingUtils::API_NAMESPACE::FloodlightActivityGroup.new( - floodlight_configuration_id: floodlight_config_id, - name: - format('Example Floodlight Activity Group #%s', SecureRandom.hex(3)), - type: 'COUNTER' - ) - - # Insert the floodlight activity group. - result = service.insert_floodlight_activity_group(profile_id, activity_group) - - # Display results. - puts format('Created floodlight activity group with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, - :floodlight_config_id) - - create_floodlight_activity_group(args[:profile_id], - args[:floodlight_config_id]) -end diff --git a/ruby/v3.5/floodlight/download_floodlight_tag.rb b/ruby/v3.5/floodlight/download_floodlight_tag.rb deleted file mode 100755 index 74df834..0000000 --- a/ruby/v3.5/floodlight/download_floodlight_tag.rb +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example downloads activity tags for a given floodlight activity. - -require_relative '../dfareporting_utils' - -def download_floodlight_tag(profile_id, activity_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct the request. - result = service.generatetag_floodlight_activity(profile_id, - floodlight_activity_id: activity_id) - - if result.global_site_tag_global_snippet.nil? - # This is an image or iframe tag. - puts format("Floodlight activity tag:\n\n%s", - result.floodlight_activity_tag) - else - # This is a global site tag, display both the global and event snippets. - puts format("Global site tag global snippet:\n\n%s", - result.global_site_tag_global_snippet) - puts format("\n\nGlobal site tag event snippet:\n\n%s", - result.floodlight_activity_tag) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :activity_id) - - download_floodlight_tag(args[:profile_id], args[:activity_id]) -end diff --git a/ruby/v3.5/floodlight/get_floodlight_activities.rb b/ruby/v3.5/floodlight/get_floodlight_activities.rb deleted file mode 100755 index c1dbfce..0000000 --- a/ruby/v3.5/floodlight/get_floodlight_activities.rb +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays floodlight activities for a given advertiser. -# -# To create an advertiser, run create_advertiser.rb. - -require_relative '../dfareporting_utils' - -def get_floodlight_activities(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_floodlight_activities(profile_id, - advertiser_id: advertiser_id, - page_token: token, - fields: 'nextPageToken,floodlightActivities(id,name)') - - # Display results. - if result.floodlight_activities.any? - result.floodlight_activities.each do |activity| - puts format('Found floodlight activity with ID %d and name "%s".', - activity.id, activity.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_floodlight_activities(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/floodlight/get_floodlight_activity_groups.rb b/ruby/v3.5/floodlight/get_floodlight_activity_groups.rb deleted file mode 100755 index 5015c48..0000000 --- a/ruby/v3.5/floodlight/get_floodlight_activity_groups.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays floodlight activity groups for a given advertiser. -# -# To create an advertiser, run create_advertiser.rb. - -require_relative '../dfareporting_utils' - -def get_floodlight_activity_groups(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_floodlight_activity_groups(profile_id, - advertiser_id: advertiser_id, - page_token: token, - fields: 'nextPageToken,floodlightActivityGroups(id,name)') - - # Display results. - if result.floodlight_activity_groups.any? - result.floodlight_activity_groups.each do |group| - puts format( - 'Found floodlight activity group with ID %d and name "%s".', - group.id, group.name - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_floodlight_activity_groups(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/misc/get_change_logs_for_advertiser.rb b/ruby/v3.5/misc/get_change_logs_for_advertiser.rb deleted file mode 100755 index 81866ea..0000000 --- a/ruby/v3.5/misc/get_change_logs_for_advertiser.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays the change logs of a specified advertiser object. -# -# A similar pattern can be applied to get change logs for many other object -# types. - -require_relative '../dfareporting_utils' - -def get_change_logs_for_advertiser(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_change_logs(profile_id, - object_ids: [advertiser_id], - object_type: 'OBJECT_ADVERTISER', - page_token: token, - fields: 'nextPageToken,changeLogs(action,fieldName,oldValue,newValue)') - - # Display results. - if result.change_logs.any? - result.change_logs.each do |log| - puts format('%s: Field "%s" from "%s" to "%s".', log.action, - log.field_name, log.old_value, log.new_value) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_change_logs_for_advertiser(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/misc/get_sites.rb b/ruby/v3.5/misc/get_sites.rb deleted file mode 100755 index 2dc8824..0000000 --- a/ruby/v3.5/misc/get_sites.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all existing sites for the current DCM account. - -require_relative '../dfareporting_utils' - -def get_subaccounts(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_sites(profile_id, - page_token: token, - fields: 'nextPageToken,sites(id,keyName)') - - # Display results. - if result.sites.any? - result.sites.each do |site| - puts format('Found site with ID %d and key name "%s".', - site.id, site.key_name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_subaccounts(args[:profile_id]) -end diff --git a/ruby/v3.5/misc/get_size.rb b/ruby/v3.5/misc/get_size.rb deleted file mode 100755 index f511d4a..0000000 --- a/ruby/v3.5/misc/get_size.rb +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all sizes for a given width and height. - -require_relative '../dfareporting_utils' - -def get_size(profile_id, width, height) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct and execute the size request. - result = service.list_sizes(profile_id, - height: height, - width: width) - - result.sizes.each do |size| - puts format('Found size with ID %d.', size.id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :width, :height) - - get_size(args[:profile_id], args[:width], args[:height]) -end diff --git a/ruby/v3.5/placements/create_content_category.rb b/ruby/v3.5/placements/create_content_category.rb deleted file mode 100755 index ace2e2e..0000000 --- a/ruby/v3.5/placements/create_content_category.rb +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a content category with the given name and description. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_content_category(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new content category resource to insert. - content_category = DfareportingUtils::API_NAMESPACE::ContentCategory.new( - name: format('Example Content Category #%s', SecureRandom.hex(3)) - ) - - # Insert the content category. - result = service.insert_content_category(profile_id, content_category) - - # Display results. - puts format('Created content category with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_content_category(args[:profile_id]) -end diff --git a/ruby/v3.5/placements/create_placement.rb b/ruby/v3.5/placements/create_placement.rb deleted file mode 100755 index aedf5ac..0000000 --- a/ruby/v3.5/placements/create_placement.rb +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates an agency paid regular placement in a given campaign. -# -# Requires the DCM site ID and campaign ID in which the placement will be -# created. To create a campaign, run create_campaign.rb. To get DCM site ID, -# run get_site.rb. - -require_relative '../dfareporting_utils' - -def create_placement(profile_id, campaign_id, site_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the campaign. - campaign = service.get_campaign(profile_id, campaign_id) - - # Create a new placement resource to insert. - placement = DfareportingUtils::API_NAMESPACE::Placement.new( - campaign_id: campaign_id, - compatibility: 'DISPLAY', - name: 'Example Placement', - payment_source: 'PLACEMENT_AGENCY_PAID', - site_id: site_id, - size: DfareportingUtils::API_NAMESPACE::Size.new( - height: 1, - width: 1 - ), - tag_formats: ['PLACEMENT_TAG_STANDARD'] - ) - - # Set the pricing schedule for the placement. - placement.pricing_schedule = - DfareportingUtils::API_NAMESPACE::PricingSchedule.new( - end_date: campaign.end_date, - pricing_type: 'PRICING_TYPE_CPM', - start_date: campaign.start_date - ) - - # Insert the placement strategy. - result = service.insert_placement(profile_id, placement) - - # Display results. - puts format('Created placement with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :site_id) - - create_placement(args[:profile_id], args[:campaign_id], args[:site_id]) -end diff --git a/ruby/v3.5/placements/create_placement_group.rb b/ruby/v3.5/placements/create_placement_group.rb deleted file mode 100755 index 43dc8aa..0000000 --- a/ruby/v3.5/placements/create_placement_group.rb +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a placement group in a given campaign. -# -# Requires the DCM site ID and campaign ID in which the placement group will be -# created. To create a campaign, run create_campaign.rb. To get DCM site ID, -# run get_site.rb. - -require_relative '../dfareporting_utils' - -def create_placement_group(profile_id, campaign_id, site_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Look up the campaign. - campaign = service.get_campaign(profile_id, campaign_id) - - # Create a new placement group resource to insert. - placement_group = DfareportingUtils::API_NAMESPACE::PlacementGroup.new( - campaign_id: campaign_id, - name: 'Example Placement Group', - placement_group_type: 'PLACEMENT_PACKAGE', - pricing_schedule: DfareportingUtils::API_NAMESPACE::PricingSchedule.new( - start_date: campaign.start_date, - end_date: campaign.end_date, - pricing_type: 'PRICING_TYPE_CPM' - ), - site_id: site_id - ) - - # Insert the placement strategy. - result = service.insert_placement_group(profile_id, placement_group) - - # Display results. - puts format('Created placement group with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :site_id) - - create_placement_group(args[:profile_id], args[:campaign_id], args[:site_id]) -end diff --git a/ruby/v3.5/placements/create_placement_strategy.rb b/ruby/v3.5/placements/create_placement_strategy.rb deleted file mode 100755 index 78b54b9..0000000 --- a/ruby/v3.5/placements/create_placement_strategy.rb +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a placement strategy with the given name. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_placement_strategy(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new placement strategy resource to insert. - strategy = DfareportingUtils::API_NAMESPACE::PlacementStrategy.new( - name: format('Example Placement Strategy #%s', SecureRandom.hex(3)) - ) - - # Insert the placement strategy. - result = service.insert_placement_strategy(profile_id, strategy) - - # Display results. - puts format('Created placement strategy with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_placement_strategy(args[:profile_id]) -end diff --git a/ruby/v3.5/placements/download_placement_tags.rb b/ruby/v3.5/placements/download_placement_tags.rb deleted file mode 100755 index 3b42efe..0000000 --- a/ruby/v3.5/placements/download_placement_tags.rb +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example downloads HTML Tags for a given campaign and placement ID. -# -# To create campaigns, run create_campaign.rb. To create placements, run -# create_placement.rb. - -require_relative '../dfareporting_utils' - -def download_placement_tags(profile_id, campaign_id, placement_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct the request. - result = service.generate_placement_tags(profile_id, - campaign_id: campaign_id, - placement_ids: [placement_id]) - - result.placement_tags.each do |tag| - tag.tag_datas.each do |data| - puts format("%s - %s\n\n", tag.placement_id, data.format) - puts format("%s\n\n", data.impression_tag) unless data.impression_tag.nil? - puts format("%s\n\n", data.click_tag) unless data.click_tag.nil? - end - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :campaign_id, - :placement_id) - - download_placement_tags(args[:profile_id], args[:campaign_id], - args[:placement_id]) -end diff --git a/ruby/v3.5/placements/get_content_categories.rb b/ruby/v3.5/placements/get_content_categories.rb deleted file mode 100755 index 018fc91..0000000 --- a/ruby/v3.5/placements/get_content_categories.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all available content categories. - -require_relative '../dfareporting_utils' - -def get_content_categories(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_content_categories(profile_id, - page_token: token, - fields: 'nextPageToken,contentCategories(id,name)') - - # Display results. - if result.content_categories.any? - result.content_categories.each do |category| - puts format('Found content category with ID %d and name "%s".', - category.id, category.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_content_categories(args[:profile_id]) -end diff --git a/ruby/v3.5/placements/get_placement_strategies.rb b/ruby/v3.5/placements/get_placement_strategies.rb deleted file mode 100755 index 60670ba..0000000 --- a/ruby/v3.5/placements/get_placement_strategies.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all available placement strategies. - -require_relative '../dfareporting_utils' - -def get_placement_strategies(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_placement_strategies(profile_id, - page_token: token, - fields: 'nextPageToken,placementStrategies(id,name)') - - # Display results. - if result.placement_strategies.any? - result.placement_strategies.each do |strategy| - puts format('Found placement strategy with ID %d and name "%s".', - strategy.id, strategy.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_placement_strategies(args[:profile_id]) -end diff --git a/ruby/v3.5/placements/get_placements.rb b/ruby/v3.5/placements/get_placements.rb deleted file mode 100755 index dc9721f..0000000 --- a/ruby/v3.5/placements/get_placements.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all available placements. - -require_relative '../dfareporting_utils' - -def get_placements(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_placements(profile_id, - page_token: token, - fields: 'nextPageToken,placements(campaignId,id,name)') - - # Display results. - if result.placements.any? - result.placements.each do |placement| - puts format( - 'Found placement with ID %d and name "%s" for campaign %d.', - placement.id, placement.name, placement.campaign_id - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_placements(args[:profile_id]) -end diff --git a/ruby/v3.5/remarketing/create_remarketing_list.rb b/ruby/v3.5/remarketing/create_remarketing_list.rb deleted file mode 100755 index c52fff0..0000000 --- a/ruby/v3.5/remarketing/create_remarketing_list.rb +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a remarketing list for a given advertiser and floodight -# activity, using a custom rule. -# -# Note: this sample assumes that the floodlight activity specified has a U1 -# custom floodlight variable. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_remarketing_list(profile_id, advertiser_id, floodlight_activity_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a list population term. - # This term matches all visitors with a U1 value exactly matching - # "test_value" - term = DfareportingUtils::API_NAMESPACE::ListPopulationTerm.new( - operator: 'STRING_EQUALS', - type: 'CUSTOM_VARIABLE_TERM', - value: 'test_value', - variable_name: 'U1' - ) - - # Add the term to a clause and the clause to a population rule. - # This rule will target all visitors who trigger the specified floodlight - # activity and satisfy the custom rule defined in the list population term. - rule = DfareportingUtils::API_NAMESPACE::ListPopulationRule.new( - floodlight_activity_id: floodlight_activity_id, - list_population_clauses: [ - DfareportingUtils::API_NAMESPACE::ListPopulationClause.new( - terms: [term] - ) - ] - ) - - # Create the remarketing list. - list = DfareportingUtils::API_NAMESPACE::RemarketingList.new( - name: format('Test remarketing list #%s', SecureRandom.hex(3)), - active: true, - advertiser_id: advertiser_id, - life_span: 30, - list_population_rule: rule - ) - - # Insert the remarketing list. - list = service.insert_remarketing_list(profile_id, list) - - # Display results. - puts format('Remarketing list with ID %d and name "%s" was created.', - list.id, list.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :floodlight_activity_id) - - create_remarketing_list(args[:profile_id], args[:advertiser_id], - args[:floodlight_activity_id]) -end diff --git a/ruby/v3.5/remarketing/get_remarketing_lists.rb b/ruby/v3.5/remarketing/get_remarketing_lists.rb deleted file mode 100755 index 776837d..0000000 --- a/ruby/v3.5/remarketing/get_remarketing_lists.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Displays all remarketing lists owned by the specified advertiser. -# -# Note: the RemarketingLists resource will only return lists owned by the -# specified advertiser. To see all lists that can be used for targeting ads -# (including those shared from other accounts or advertisers), use the -# TargetableRemarketingLists resource instead. - -require_relative '../dfareporting_utils' - -def get_remarketing_lists(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_remarketing_lists(profile_id, advertiser_id, - page_token: token, - fields: 'nextPageToken,remarketingLists(id,name)') - - # Display results. - if result.remarketing_lists.any? - result.remarketing_lists.each do |list| - puts format('Found remarketing list with ID %d and name "%s".', - list.id, list.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - get_remarketing_lists(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/remarketing/share_remarketing_list_to_advertiser.rb b/ruby/v3.5/remarketing/share_remarketing_list_to_advertiser.rb deleted file mode 100755 index 4b201bc..0000000 --- a/ruby/v3.5/remarketing/share_remarketing_list_to_advertiser.rb +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example shares an existing remarketing list with the specified -# advertiser. - -require_relative '../dfareporting_utils' - -def share_remarketing_list_to_advertiser(profile_id, advertiser_id, - remarketing_list_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Load the existing share info. - share = service.get_remarketing_list_share(profile_id, remarketing_list_id) - share.shared_advertiser_ids ||= [] - - if share.shared_advertiser_ids.include?(advertiser_id) - puts format('Remarketing list %d is already shared to advertiser %d.', - remarketing_list_id, advertiser_id) - else - share.shared_advertiser_ids <<= advertiser_id - - # Update the share info with the newly added advertiser ID. - share = service.update_remarketing_list_share(profile_id, share) - - puts format('Remarketing list %d is now shared to advertiser ID(s): %s', - remarketing_list_id, share.shared_advertiser_ids.join(', ')) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, - :remarketing_list_id) - - share_remarketing_list_to_advertiser(args[:profile_id], args[:advertiser_id], - args[:remarketing_list_id]) -end diff --git a/ruby/v3.5/remarketing/target_ad_to_remarketing_list.rb b/ruby/v3.5/remarketing/target_ad_to_remarketing_list.rb deleted file mode 100755 index c7b8230..0000000 --- a/ruby/v3.5/remarketing/target_ad_to_remarketing_list.rb +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2017, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example targets an ad to a remarketing list. -# -# The first targetable remarketing list, either owned by or shared to the ad's -# advertiser, will be used. To create a remarketing list, see -# create_remarketing_list.rb. To share a remarketing list with the ad's -# advertiser, see share_remarketing_list_to_advertiser.rb. - -require_relative '../dfareporting_utils' - -def target_ad_to_remarketing_list(profile_id, ad_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the ad. - ad = service.get_ad(profile_id, ad_id) - - # Retrieve a single targetable remarketing list for the ad. - lists = service.list_targetable_remarketing_lists(profile_id, - ad.advertiser_id, max_results: 1) - - if lists.targetable_remarketing_lists.any? - list = lists.targetable_remarketing_lists.first - - # Update the ad with a list targeting expression. - ad.remarketing_list_expression = - DfareportingUtils::API_NAMESPACE::ListTargetingExpression.new( - expression: list.id - ) - - ad = service.update_ad(profile_id, ad) - - puts format('Ad %d updated to use remarketing list expression: "%s".', - ad.id, ad.remarketing_list_expression.expression) - else - puts format('No targetable remarketing lists found for ad with ID %d.', - ad_id) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :ad_id) - - target_ad_to_remarketing_list(args[:profile_id], args[:ad_id]) -end diff --git a/ruby/v3.5/reports/create_report.rb b/ruby/v3.5/reports/create_report.rb deleted file mode 100755 index 02c51b1..0000000 --- a/ruby/v3.5/reports/create_report.rb +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# An end-to-end example of how to create and configure a standard report. - -require_relative '../dfareporting_utils' -require 'date' - -def create_report(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # 1. Create a report resource. - report = create_report_resource - - # 2. Define report criteria. - define_report_criteria(report) - - # 3. (optional) Look up compatible fields. - find_compatible_fields(service, profile_id, report) - - # 4. Add dimension filers to the report criteria. - add_dimension_filters(service, profile_id, report) - - # 5. Save the report resource. - insert_report_resource(service, profile_id, report) -end - -def create_report_resource - report = DfareportingUtils::API_NAMESPACE::Report.new( - # Set the required fields "name" and "type". - name: 'Example Standard Report', - type: 'STANDARD', - # Set optional fields. - file_name: 'example_report', - format: 'CSV' - ) - - puts format('Creating %s report resource with name "%s".', report.type, - report.name) - - report -end - -def define_report_criteria(report) - # Define a date range to report on. This example uses explicit start and end - # dates to mimic the "LAST_30_DAYS" relative date range. - start_date = DateTime.now.prev_day(30).strftime('%Y-%m-%d') - end_date = DateTime.now.strftime('%Y-%m-%d') - - # Create a report criteria - criteria = DfareportingUtils::API_NAMESPACE::Report::Criteria.new( - date_range: DfareportingUtils::API_NAMESPACE::DateRange.new( - start_date: start_date, - end_date: end_date - ), - dimensions: [ - DfareportingUtils::API_NAMESPACE::SortedDimension.new( - name: 'advertiser' - ) - ], - metric_names: ['clicks', 'impressions'] - ) - - # Add the criteria to the report resource. - report.criteria = criteria - - puts format("\nAdded report criteria:\n%s", criteria.to_json) -end - -def find_compatible_fields(service, profile_id, report) - fields = service.query_report_compatible_field(profile_id, report) - - report_fields = fields.report_compatible_fields - - if report_fields.dimensions.any? - # Add a compatible dimension to the report. - report.criteria.dimensions << - DfareportingUtils::API_NAMESPACE::SortedDimension.new( - name: report_fields.dimensions.first.name - ) - elsif report_fields.metrics.any? - # Add a compatible metric to the report. - report.criteria.metric_names << report_fields.metrics.first.name - end - - puts format("\nUpdated report criteria (with compatible fields):\n%s", - report.criteria.to_json) -end - -def add_dimension_filters(service, profile_id, report) - # Query advertiser dimension values for report run dates. - dimension = DfareportingUtils::API_NAMESPACE::DimensionValueRequest.new( - dimension_name: 'advertiser', - start_date: report.criteria.date_range.start_date, - end_date: report.criteria.date_range.end_date - ) - - values = service.query_dimension_value(profile_id, dimension) - - unless values.items.empty? - # Add a value as a filter to the report criteria. - report.criteria.dimension_filters = [values.items.first] - end - - puts format("\nUpdated report criteria (with valid dimension filters):\n%s", - report.criteria.to_json) -end - -def insert_report_resource(service, profile_id, report) - report = service.insert_report(profile_id, report) - - puts format("\nSuccessfully inserted new report with ID %s.", report.id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - create_report(args[:profile_id]) -end diff --git a/ruby/v3.5/reports/delete_report.rb b/ruby/v3.5/reports/delete_report.rb deleted file mode 100755 index 1947df4..0000000 --- a/ruby/v3.5/reports/delete_report.rb +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to delete a report. - -require_relative '../dfareporting_utils' - -def delete_report(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Delete the report. - service.delete_report(profile_id, report_id) - - puts format('Successfully deleted report with ID %d.', report_id) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - delete_report(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.5/reports/download_file.rb b/ruby/v3.5/reports/download_file.rb deleted file mode 100755 index 671ce68..0000000 --- a/ruby/v3.5/reports/download_file.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to download a file - -require_relative '../dfareporting_utils' - -def download_file(report_id, file_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the file metadata. - report_file = service.get_file(report_id, file_id) - return unless report_file.status == 'REPORT_AVAILABLE' - - # Prepare a local file to download the report contents to. - File.open(generate_file_name(report_file), 'w') do |out_file| - # Execute the download request. Providing a download destination - # retrieves the file contents rather than the file metadata. - service.get_file(report_id, file_id, download_dest: out_file) - - puts format('File %s downloaded to %s', file_id, - File.absolute_path(out_file.path)) - end -end - -def generate_file_name(report_file) - file_name = report_file.file_name - # If no filename is specified, use the file ID instead. - file_name = report_file.id.to_s if file_name.empty? - extension = report_file.format == 'CSV' ? '.csv' : '.xml' - file_name + extension -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :report_id, :file_id) - - download_file(args[:report_id], args[:file_id]) -end diff --git a/ruby/v3.5/reports/find_and_download_file.rb b/ruby/v3.5/reports/find_and_download_file.rb deleted file mode 100755 index a7f93a3..0000000 --- a/ruby/v3.5/reports/find_and_download_file.rb +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2018, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# An end-to-end example of how to find and download a report file. - -require_relative '../dfareporting_utils' - -def find_and_download_file(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # 1. Find a file to download. - report_file = find_file(service, profile_id, report_id) - - if report_file - # 2. (optional) Generate a browser URL. - generate_browser_url(service, report_id, report_file.id) - - # 3. Directly download the file. - direct_download_file(service, report_id, report_file.id) - else - puts format('No file found for profile ID %d and report ID %d.', - profile_id, report_id) - end -end - -def find_file(service, profile_id, report_id) - page_token = nil - target = nil - - loop do - result = service.list_report_files(profile_id, report_id, - page_token: page_token) - - result.items.each do |file| - if target_file?(file) - target = file - break - end - end - - page_token = (result.next_page_token if target.nil? && result.items.any?) - break if page_token.to_s.empty? - end - - if target - puts format('Found file %s with filename "%s".', target.id, - target.file_name) - return target - end - - puts format('Unable to find file for profile ID %d and report ID %d.', - profile_id, report_id) - nil -end - -def target_file?(file) - # Provide custom validation logic here. - # For example purposes, any available file is considered valid. - file.status == 'REPORT_AVAILABLE' -end - -def generate_browser_url(service, report_id, file_id) - report_file = service.get_file(report_id, file_id) - browser_url = report_file.urls.browser_url - - puts format('File %s has browser URL: %s.', report_file.id, browser_url) -end - -def direct_download_file(service, report_id, file_id) - # Retrieve the file metadata. - report_file = service.get_file(report_id, file_id) - return unless report_file.status == 'REPORT_AVAILABLE' - - # Prepare a local file to download the report contents to. - File.open(generate_file_name(report_file), 'w') do |out_file| - # Execute the download request. Providing a download destination - # retrieves the file contents rather than the file metadata. - service.get_file(report_id, file_id, download_dest: out_file) - - puts format('File %s downloaded to %s', file_id, - File.absolute_path(out_file.path)) - end -end - -def generate_file_name(report_file) - file_name = report_file.file_name - # If no filename is specified, use the file ID instead. - file_name = report_file.id.to_s if file_name.empty? - extension = report_file.format == 'CSV' ? '.csv' : '.xml' - file_name + extension -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - find_and_download_file(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.5/reports/find_and_run_report.rb b/ruby/v3.5/reports/find_and_run_report.rb deleted file mode 100755 index 439cb35..0000000 --- a/ruby/v3.5/reports/find_and_run_report.rb +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright (C) 2016 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# An end-to-end example of how to find and run a report. - -require_relative '../dfareporting_utils' - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - -def find_and_run_report(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # 1. Find a report to run. - report = find_report(service, profile_id) - - if report - # 2. Run the report. - report_file = run_report(service, profile_id, report.id) - - # 3. Wait for the report file to be ready. - wait_for_report_file(service, report.id, report_file.id) - else - puts format('No report found for profile ID %d.', profile_id) - end -end - -def find_report(service, profile_id) - page_token = nil - target = nil - - loop do - result = service.list_reports(profile_id, page_token: page_token) - - result.items.each do |report| - if target_report?(report) - target = report - break - end - end - - page_token = (result.next_page_token if target.nil? && result.items.any?) - break if page_token.to_s.empty? - end - - if target - puts format('Found report %s with filename "%s".', target.id, - target.file_name) - return target - end - - puts format('Unable to find report for profile ID %d.', profile_id) - nil -end - -def target_report?(report) - # Provide custom validation logic here. - # For example purposes, any report is considered valid. - !report.nil? -end - -def run_report(service, profile_id, report_id) - # Run the report. - report_file = service.run_report(profile_id, report_id) - - puts format('Running report %d, current file status is %s.', report_id, - report_file.status) - report_file -end - -def wait_for_report_file(service, report_id, file_id) - # Wait for the report file to finish processing. - # An exponential backoff strategy is used to conserve request quota. - interval = 0 - start_time = Time.now - loop do - report_file = service.get_file(report_id, file_id) - - status = report_file.status - if status == 'REPORT_AVAILABLE' - puts format('File status is %s, ready to download.', status) - break - elsif status != 'PROCESSING' - puts format('File status is %s, processing failed.', status) - break - elsif Time.now - start_time > MAX_RETRY_ELAPSED_TIME - puts 'File processing deadline exceeded.' - break - end - - interval = next_sleep_interval(interval) - puts format('File status is %s, sleeping for %d seconds.', status, - interval) - sleep(interval) - end -end - -def next_sleep_interval(previous_interval) - min_interval = [MIN_RETRY_INTERVAL, previous_interval].max - max_interval = [MIN_RETRY_INTERVAL, previous_interval * 3].max - [MAX_RETRY_INTERVAL, rand(min_interval..max_interval)].min -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - find_and_run_report(args[:profile_id]) -end diff --git a/ruby/v3.5/reports/get_compatible_fields.rb b/ruby/v3.5/reports/get_compatible_fields.rb deleted file mode 100755 index 548bace..0000000 --- a/ruby/v3.5/reports/get_compatible_fields.rb +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to get the compatible fields for a report. - -require_relative '../dfareporting_utils' - -def get_compatible_fields(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Get the report. - report = service.get_report(profile_id, report_id) - - # Get the compatible fields. - result = service.query_report_compatible_field(profile_id, report) - - compatible_fields = result.report_compatible_fields - - # Display dimensions. - dimensions = compatible_fields.dimensions.map(&:name) - print_fields('Dimensions', dimensions) - - # Display metrics. - metrics = compatible_fields.metrics.map(&:name) - print_fields('Metrics', metrics) - - # Display dimension filters. - filters = compatible_fields.dimension_filters.map(&:name) - print_fields('Dimension Filers', filters) - - # Display pivoted activity metrics. - activities = compatible_fields.pivoted_activity_metrics.map(&:name) - print_fields('Pivoted Activity Metrics', activities) -end - -def print_fields(type, fields) - puts format('Compatible %s', type) - puts fields.join(', ') - puts -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - get_compatible_fields(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.5/reports/get_dimension_values.rb b/ruby/v3.5/reports/get_dimension_values.rb deleted file mode 100755 index b2f9ed6..0000000 --- a/ruby/v3.5/reports/get_dimension_values.rb +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all values for a dimension - -require_relative '../dfareporting_utils' -require 'date' - -def get_dimension_values(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create the dimension to query. - dimension = DfareportingUtils::API_NAMESPACE::DimensionValueRequest.new( - dimension_name: 'advertiser', - start_date: DateTime.now.prev_year.strftime('%Y-%m-%d'), - end_date: DateTime.now.strftime('%Y-%m-%d') - ) - - token = nil - loop do - result = service.query_dimension_value( - profile_id, dimension, - page_token: token, - fields: 'nextPageToken,items(id,value)' - ) - - # Display results. - if result.items.any? - result.items.each do |dimension_value| - puts format('Dimension with ID %d and value "%s" was found.', - dimension_value.id, dimension_value.value) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_dimension_values(args[:profile_id]) -end diff --git a/ruby/v3.5/reports/get_files.rb b/ruby/v3.5/reports/get_files.rb deleted file mode 100755 index e2a444e..0000000 --- a/ruby/v3.5/reports/get_files.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all files for a profile - -require_relative '../dfareporting_utils' - -def get_files(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_files(profile_id, - page_token: token, - fields: 'nextPageToken,items(fileName,id,status)') - - # Display results. - if result.items.any? - result.items.each do |file| - puts format( - 'Report file with ID %d and file name "%s" has status "%s".', - file.id, file.file_name, file.status - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_files(args[:profile_id]) -end diff --git a/ruby/v3.5/reports/get_report_files.rb b/ruby/v3.5/reports/get_report_files.rb deleted file mode 100755 index 9a7e027..0000000 --- a/ruby/v3.5/reports/get_report_files.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all files for a report - -require_relative '../dfareporting_utils' - -def get_report_files(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_report_files(profile_id, report_id, - page_token: token, - fields: 'nextPageToken,items(fileName,id,status)') - - # Display results. - if result.items.any? - result.items.each do |file| - puts format( - 'Report file with ID %d and file name "%s" has status "%s".', - file.id, file.file_name, file.status - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - get_report_files(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.5/reports/get_reports.rb b/ruby/v3.5/reports/get_reports.rb deleted file mode 100755 index 9dd22f3..0000000 --- a/ruby/v3.5/reports/get_reports.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all reports for a profile - -require_relative '../dfareporting_utils' - -def get_reports(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_reports(profile_id, - page_token: token, - fields: 'nextPageToken,items(id,name,type)') - - # Display results. - if result.items.any? - result.items.each do |report| - puts format('%s report with ID %d and name "%s" was found.', - report.type, report.id, report.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_reports(args[:profile_id]) -end diff --git a/ruby/v3.5/reports/run_report.rb b/ruby/v3.5/reports/run_report.rb deleted file mode 100755 index fe771a1..0000000 --- a/ruby/v3.5/reports/run_report.rb +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright (C) 2016 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to run a report. - -require_relative '../dfareporting_utils' - -# The following values control retry behavior while the report is processing. -# Minimum amount of time between polling requests. Defaults to 10 seconds. -MIN_RETRY_INTERVAL = 10 -# Maximum amount of time between polling requests. Defaults to 10 minutes. -MAX_RETRY_INTERVAL = 10 * 60 -# Maximum amount of time to spend polling. Defaults to 1 hour. -MAX_RETRY_ELAPSED_TIME = 60 * 60 - -def run_report(profile_id, report_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Run the report. - report_file = service.run_report(profile_id, report_id) - puts format('File with ID %s has been created.', report_file.id) - - # Wait for the report to finish processing. - wait_for_report_file(service, report_id, report_file.id) -end - -def wait_for_report_file(service, report_id, file_id) - # An exponential backoff strategy is used to conserve request quota. - interval = 0 - start_time = Time.now - loop do - report_file = service.get_file(report_id, file_id) - - status = report_file.status - if status == 'REPORT_AVAILABLE' - puts format('File status is %s, ready to download.', status) - break - elsif status != 'PROCESSING' - puts format('File status is %s, processing failed.', status) - break - elsif Time.now - start_time > MAX_RETRY_ELAPSED_TIME - puts 'File processing deadline exceeded.' - break - end - - interval = next_sleep_interval(interval) - puts format('File status is %s, sleeping for %d seconds.', status, interval) - sleep(interval) - end -end - -def next_sleep_interval(previous_interval) - min_interval = [MIN_RETRY_INTERVAL, previous_interval].max - max_interval = [MIN_RETRY_INTERVAL, previous_interval * 3].max - [MAX_RETRY_INTERVAL, rand(min_interval..max_interval)].min -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :report_id) - - run_report(args[:profile_id], args[:report_id]) -end diff --git a/ruby/v3.5/subaccounts/create_subaccount.rb b/ruby/v3.5/subaccounts/create_subaccount.rb deleted file mode 100755 index 0516b31..0000000 --- a/ruby/v3.5/subaccounts/create_subaccount.rb +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a subaccount in a given DCM account. -# -# To get the account ID, run get_all_userprofiles.rb. To get the available -# permissions, run get_subaccount_permissions.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_subaccount(profile_id, account_id, permission_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new subaccount resource to insert. - subaccount = DfareportingUtils::API_NAMESPACE::Subaccount.new( - account_id: account_id, - available_permission_ids: [permission_id], - name: format('Example Subaccount #%s', SecureRandom.hex(3)) - ) - - # Insert the subaccount. - result = service.insert_subaccount(profile_id, subaccount) - - # Display results. - puts format('Created subaccount with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :account_id, - :permission_id) - - create_subaccount(args[:profile_id], args[:account_id], args[:permission_id]) -end diff --git a/ruby/v3.5/subaccounts/get_subaccount_permissions.rb b/ruby/v3.5/subaccounts/get_subaccount_permissions.rb deleted file mode 100755 index 23559ee..0000000 --- a/ruby/v3.5/subaccounts/get_subaccount_permissions.rb +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all of the available user role permissions for a given -# subaccount. -# -# To get a subaccount ID, run get_subaccounts.rb. - -require_relative '../dfareporting_utils' - -def get_subaccount_permissions(profile_id, subaccount_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Construct and execute the subaccount request. - subaccount = service.get_subaccount(profile_id, subaccount_id) - - # Construct the user role permissions request. - result = service.list_user_role_permissions(profile_id, - ids: subaccount.available_permission_ids) - - result.user_role_permissions.each do |permission| - puts format('Found user role permission with ID %d and name "%s".', - permission.id, permission.name) - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :subaccount_id) - - get_subaccount_permissions(args[:profile_id], args[:subaccount_id]) -end diff --git a/ruby/v3.5/subaccounts/get_subaccounts.rb b/ruby/v3.5/subaccounts/get_subaccounts.rb deleted file mode 100755 index a18a9b1..0000000 --- a/ruby/v3.5/subaccounts/get_subaccounts.rb +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all subaccounts. -# -# Note that the permissions assigned to a subaccount are not returned in a -# human-readable format with this example. Run get_available_permissions.rb to -# see what permissions are available on a subaccount. - -require_relative '../dfareporting_utils' - -def get_subaccounts(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_subaccounts(profile_id, - page_token: token, - fields: 'nextPageToken,subaccounts(id,name)') - - # Display results. - if result.subaccounts.any? - result.subaccounts.each do |subaccount| - puts format('Found subaccount with ID %d and name "%s".', subaccount.id, - subaccount.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_subaccounts(args[:profile_id]) -end diff --git a/ruby/v3.5/targeting/configure_dynamic_asset_selection.rb b/ruby/v3.5/targeting/configure_dynamic_asset_selection.rb deleted file mode 100755 index c2596c0..0000000 --- a/ruby/v3.5/targeting/configure_dynamic_asset_selection.rb +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example enables dynamic asset selection for an in-stream video creative. -# -# Requires an existing in-stream video creative, a new video asset, and a -# targeting template ID as input. To get an in-stream video creative, run -# create_instream_video_creative.rb. To get a targeting template, run -# create_targeting_template.rb. - -require_relative '../creative_asset_utils' -require_relative '../dfareporting_utils' - -def configure_dynamic_asset_selection(profile_id, creative_id, template_id, - path_to_video_file) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Retrieve the specified creative. - creative = service.get_creative(profile_id, creative_id) - - abort 'Invalid creative specified' if - creative.nil? || (creative.type != 'INSTREAM_VIDEO') - - # Enable dynamic asset selection for the creative if necessary. - enable_dynamic_asset_selection(creative) unless - creative.dynamic_asset_selection? - - # Upload the new video asset and add it to the creative. - video_asset = CreativeAssetUtils.new(service, profile_id).upload_asset( - creative.advertiser_id, path_to_video_file, 'VIDEO' - ) - - creative.creative_assets <<= - DfareportingUtils::API_NAMESPACE::CreativeAsset.new( - asset_identifier: video_asset.asset_identifier, - role: 'PARENT_VIDEO' - ) - - # Create a rule targeting the new video asset and add it to the creative. - creative.creative_asset_selection.rules <<= - DfareportingUtils::API_NAMESPACE::Rule.new( - asset_id: video_asset.id, - name: format('Test rule for asset %d', video_asset.id), - targeting_template_id: template_id - ) - - result = service.update_creative(profile_id, creative) - - puts format('Dynamic asset selection enabled for creative with ID %d.', - result.id) -end - -def enable_dynamic_asset_selection(creative) - # Locate an existing video asset to use as a default. - default_asset = creative.creative_assets.find do |asset| - asset.role == 'PARENT_VIDEO' - end - - abort 'Default video asset could not be found.' if default_asset.nil? - - # Enable dynamic asset selection for the creative. - creative.dynamic_asset_selection = true - - # Create a new selection using the existing asset as a default. - creative.creative_asset_selection = - DfareportingUtils::API_NAMESPACE::CreativeAssetSelection.new( - default_asset_id: default_asset.id, - rules: [] - ) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :creative_id, - :template_id, :path_to_video_file) - - configure_dynamic_asset_selection(args[:profile_id], args[:creative_id], - args[:template_id], args[:path_to_video_file]) -end diff --git a/ruby/v3.5/targeting/create_targeting_template.rb b/ruby/v3.5/targeting/create_targeting_template.rb deleted file mode 100755 index 1e1b603..0000000 --- a/ruby/v3.5/targeting/create_targeting_template.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a targeting template associated with a given advertiser. -# -# To get an advertiser ID, run get_advertisers.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_targeting_template(profile_id, advertiser_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new targeting template resource to insert. - # This template will be configured to serve ads on Monday, Wednesday, and - # Friday from 9-10am and 3-5pm. - # Note: targeting template names must be unique within an advetiser. - targeting_template = DfareportingUtils::API_NAMESPACE::TargetingTemplate.new( - advertiser_id: advertiser_id, - day_part_targeting: DfareportingUtils::API_NAMESPACE::DayPartTargeting.new( - days_of_week: %w[MONDAY WEDNESDAY FRIDAY], - hours_of_day: [9, 15, 16], - user_local_time: true - ), - name: format('Test Targeting Template #%s', SecureRandom.hex(3)) - ) - - # Insert the targeting template. - result = service.insert_targeting_template(profile_id, targeting_template) - - # Display results. - puts format('Created targeting template with ID %d and name "%s".', - result.id, result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id) - - create_targeting_template(args[:profile_id], args[:advertiser_id]) -end diff --git a/ruby/v3.5/targeting/get_targeting_templates.rb b/ruby/v3.5/targeting/get_targeting_templates.rb deleted file mode 100755 index fffa481..0000000 --- a/ruby/v3.5/targeting/get_targeting_templates.rb +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example retrieves all targeting templates for your DCM user profile. -# -# Displays name, ID, and advertiser ID for each targeting template found. - -require_relative '../dfareporting_utils' - -def get_targeting_templates(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_targeting_templates(profile_id, - page_token: token, - fields: 'nextPageToken,targetingTemplates(advertiserId,id,name)') - - # Display results. - if result.targeting_templates.any? - result.targeting_templates.each do |template| - puts format( - 'Found targeting template with ID %d and name "%s" associated with ' \ - 'advertiser ID %d.', template.id, template.name, - template.advertiser_id - ) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_targeting_templates(args[:profile_id]) -end diff --git a/ruby/v3.5/user_profiles/get_user_profiles.rb b/ruby/v3.5/user_profiles/get_user_profiles.rb deleted file mode 100755 index 6752b7b..0000000 --- a/ruby/v3.5/user_profiles/get_user_profiles.rb +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example illustrates how to list all user profiles - -require_relative '../dfareporting_utils' - -def get_user_profiles - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Get all user profiles. - result = service.list_user_profiles - - # Display results. - result.items.each do |profile| - puts format( - 'User profile with ID %d and name "%s" was found for account %d.', - profile.profile_id, profile.user_name, profile.account_id - ) - end -end - -get_user_profiles if $PROGRAM_NAME == __FILE__ diff --git a/ruby/v3.5/user_roles/create_user_role.rb b/ruby/v3.5/user_roles/create_user_role.rb deleted file mode 100755 index 2d3aecf..0000000 --- a/ruby/v3.5/user_roles/create_user_role.rb +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example creates a user role in a given DCM account. -# -# To get the account ID, run get_all_userprofiles.rb. To get the parent user -# role ID, run get_user_roles.rb. - -require_relative '../dfareporting_utils' -require 'securerandom' - -def create_user_role(profile_id, account_id, parent_role_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - # Create a new user role resource to insert. - user_role = DfareportingUtils::API_NAMESPACE::UserRole.new( - account_id: account_id, - name: format('Example User Role #%s', SecureRandom.hex(3)), - parent_user_role_id: parent_role_id - ) - - # Insert the user role. - result = service.insert_user_role(profile_id, user_role) - - # Display results. - puts format('Created user role with ID %d and name "%s".', result.id, - result.name) -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :account_id, - :parent_role_id) - - create_user_role(args[:profile_id], args[:account_id], - args[:parent_role_id]) -end diff --git a/ruby/v3.5/user_roles/get_user_roles.rb b/ruby/v3.5/user_roles/get_user_roles.rb deleted file mode 100755 index 9faf8f2..0000000 --- a/ruby/v3.5/user_roles/get_user_roles.rb +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env ruby - -# -# Copyright:: Copyright 2016, Google Inc. All Rights Reserved. -# -# License:: Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This example displays all user roles. - -require_relative '../dfareporting_utils' - -def get_user_roles(profile_id) - # Authenticate and initialize API service. - service = DfareportingUtils.initialize_service - - token = nil - loop do - result = service.list_user_roles(profile_id, - page_token: token, - fields: 'nextPageToken,userRoles(id,name)') - - # Display results. - if result.user_roles.any? - result.user_roles.each do |role| - puts format('Found user role with ID %d and name "%s".', role.id, - role.name) - end - - token = result.next_page_token - else - # Stop paging if there are no more results. - token = nil - end - - break if token.to_s.empty? - end -end - -if $PROGRAM_NAME == __FILE__ - # Retrieve command line arguments. - args = DfareportingUtils.parse_arguments(ARGV, :profile_id) - - get_user_roles(args[:profile_id]) -end