private void GetReportFields_Click(object sender, EventArgs e) { Dictionary <string, string> headers = new Dictionary <string, string>() { { "DeveloperToken", this.DeveloperToken.Text }, { "UserAgent", String.Format("Edge File Manager (version {0})", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()) }, { "EnableGzipCompression", this.EnableGzipCompression.Text }, { "ClientCustomerId", this.ClientCustomerId.Text }, { "Email", this.Email.Text } }; User = new AdWordsUser(headers); try { //Getting AuthToken (User.Config as AdWordsAppConfig).AuthToken = AdwordsUtill.GetAuthToken(User); ReportDefinitionReportType reportType = (ReportDefinitionReportType)Enum.Parse(typeof(ReportDefinitionReportType), ReportNamesListBox.SelectedItem.ToString()); ReportDefinitionService reportDefinitionService = (ReportDefinitionService)User.GetService(AdWordsService.v201302.ReportDefinitionService); // Get the report fields. ReportDefinitionField[] reportDefinitionFields = reportDefinitionService.getReportFields(reportType); foreach (ReportDefinitionField reportDefinitionField in reportDefinitionFields) { this.AvailableReportFields.AppendText(reportDefinitionField.fieldName + ","); List <object> rowObjects = new List <object>(); this.dataGridView.Rows.Add( reportDefinitionField.fieldName, reportDefinitionField.displayFieldName, reportDefinitionField.fieldType, reportDefinitionField.isBeta, reportDefinitionField.canFilterSpecified, reportDefinitionField.canSelect, reportDefinitionField.canSelectSpecified, reportDefinitionField.enumValuePairs, reportDefinitionField.enumValues, reportDefinitionField.isBetaSpecified, reportDefinitionField.isEnumType, reportDefinitionField.isEnumTypeSpecified, reportDefinitionField.xmlAttributeName, reportDefinitionField.canFilter); } this.AvailableReportFields.Text.Remove(this.AvailableReportFields.Text.Length - 1, 1); } catch (Exception ex) { this.response.Text = string.Format("{0} Inner: {1}", ex.Message, ex.InnerException.Message); } }
protected override ServiceOutcome DoPipelineWork() { foreach (var clientId in (string[])Delivery.Parameters["AdwordsClientIDs"]) { //Get all files on specific client var files = Delivery.Files.Where(x => x.Parameters["AdwordsClientID"].ToString() == clientId); //Setting Adwords User and AuthToken var headers = new Dictionary <string, string> { { "DeveloperToken", Delivery.Parameters["DeveloperToken"].ToString() }, { "UserAgent", FileManager.UserAgentString }, { "EnableGzipCompression", "true" }, { "ClientCustomerId", clientId }, { "Email", Delivery.Parameters["MccEmail"].ToString() } }; var adwrodsUser = new AdWordsUser(headers); var config = adwrodsUser.Config as AdWordsAppConfig; if (config == null) { throw new Exception("Failed to convert AdwordUser.Config to AdWordsAppConfig"); } config.AuthToken = AdwordsUtill.GetAuthToken(adwrodsUser); var counter = 0; foreach (var file in files) { counter++; // retrieve data using retriever of specific type var retriever = GetRetrieverByType(file.Parameters["ReportType"].ToString()); var data = retriever.RetrieveData(file, adwrodsUser); // save retrieved data to file file.Location = file.CreateLocation(); var fullPath = Path.Combine(AppSettings.Get(typeof(FileManager), "RootPath"), file.Location); if (!Directory.Exists(Path.GetDirectoryName(fullPath))) { Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); } File.WriteAllLines(fullPath, data); Progress = (double)counter / files.Count(); } } Delivery.Save(); return(ServiceOutcome.Success); }
private WebRequest CreateAdwordsReportRequest(DeliveryFile file, AdWordsUser user, string postBody) { var config = user.Config as AdWordsAppConfig; var request = WebRequest.Create(file.SourceUrl) as HttpWebRequest; if (config == null || request == null) { return(null); } request.Timeout = 100000; if (!string.IsNullOrEmpty(postBody)) { request.Method = "POST"; } if (!string.IsNullOrEmpty(config.ClientCustomerId)) { request.Headers.Add("clientCustomerId: " + (user.Config as AdWordsAppConfig).ClientCustomerId); } request.ContentType = "application/x-www-form-urlencoded"; if (config.EnableGzipCompression) { request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } else { request.AutomaticDecompression = DecompressionMethods.None; } if (config.AuthorizationMethod == AdWordsAuthorizationMethod.ClientLogin) { string authToken = AdwordsUtill.GetAuthToken(user); (user.Config as AdWordsAppConfig).AuthToken = authToken; request.Headers["Authorization"] = "GoogleLogin auth=" + authToken; } request.Headers.Add("returnMoneyInMicros: true"); request.Headers.Add("developerToken: " + (user.Config as AdWordsAppConfig).DeveloperToken); //Try to unmark the following comment in case of api error //The client library will use only apiMode = true. //request.Headers.Add("apiMode", "true"); return(request); }
protected override ServiceOutcome DoPipelineWork() { _batchDownloadOperation = new BatchDownloadOperation { MaxConcurrent = 1 }; _batchDownloadOperation.Progressed += _batchDownloadOperation_Progressed; var includeZeroImpression = Boolean.Parse(Delivery.Parameters["includeZeroImpression"].ToString()); // time period var startDate = Delivery.TimePeriodDefinition.Start.ToDateTime().ToString("yyyyMMdd"); var endDate = Delivery.TimePeriodDefinition.End.ToDateTime().ToString("yyyyMMdd"); foreach (var clientId in (string[])Delivery.Parameters["AdwordsClientIDs"]) { //Get all files on specific client var files = Delivery.Files.Where(x => x.Parameters["AdwordsClientID"].ToString() == clientId); //Setting Adwords User var headers = new Dictionary <string, string> { { "DeveloperToken", Delivery.Parameters["DeveloperToken"].ToString() }, { "UserAgent", FileManager.UserAgentString }, { "EnableGzipCompression", "true" }, { "ClientCustomerId", clientId }, { "Email", Delivery.Parameters["MccEmail"].ToString() } }; var user = new AdWordsUser(headers); // AuthToken var config = user.Config as AdWordsAppConfig; if (config == null) { throw new Exception("Failed to convert AdwordUser.Config to AdWordsAppConfig"); } config.AuthToken = AdwordsUtill.GetAuthToken(user); var firstCheck = true; var awqls = new List <string>(); foreach (var file in files) { // report type if (!Enum.IsDefined(typeof(GA201302.ReportDefinitionReportType), file.Parameters["ReportType"].ToString())) { throw new ConfigurationErrorsException(String.Format("Unknown Google Adwords Report Type '{0}'", file.Parameters["ReportType"])); } // Creating AWQL var sb = new StringBuilder(); sb.AppendFormat("SELECT {0} FROM {1}", file.Parameters["ReportFields"], file.Parameters["ReportType"]); if (!includeZeroImpression) { sb.Append(" WHERE Impressions > 0"); } sb.AppendFormat(" DURING {0},{1}", startDate, endDate); var format = GA201302.DownloadFormat.GZIPPED_CSV.ToString(); file.SourceUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer, REPORT_VERSION, format); var query = sb.ToString(); var postData = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query)); awqls.Add(query); //Validate Report if (firstCheck) { string error; if (!ValidateReport(file, user, postData, out error)) { //CHEKING FOR INVALID AUTHTOKEN if (error.Contains(GA201302.AuthenticationErrorReason.GOOGLE_ACCOUNT_COOKIE_INVALID.ToString())) { //RENEWING AUTHTOKEN config.AuthToken = AdwordsUtill.GetAuthToken(user, generateNew: true); } else { throw new Exception(String.Format("Google Adwords API Error: {0}", error)); } } firstCheck = false; } //If Validate - Success DownloadFile(file, user, postData); } } Progress = 0.2; _batchDownloadOperation.Start(); _batchDownloadOperation.Wait(); _batchDownloadOperation.EnsureSuccess(); //INCASE OF GENERAL EXCEPTION OPEN DELIVERY FILE HAS HTML AND VIEW INNER ERROR Progress = 0.9; Delivery.Save(); return(ServiceOutcome.Success); }
private void GetAgSettings2_Click(object sender, EventArgs e) { Dictionary <string, string> headers = new Dictionary <string, string>() { { "DeveloperToken", this.DeveloperToken.Text }, { "UserAgent", String.Format("Edge File Manager (version {0})", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()) }, { "EnableGzipCompression", this.EnableGzipCompression.Text }, { "ClientCustomerId", this.ClientCustomerId.Text }, { "Email", this.Email.Text } }; User = new AdWordsUser(headers); try { //Getting AuthToken (User.Config as AdWordsAppConfig).AuthToken = AdwordsUtill.GetAuthToken(User); } catch (Exception exc) { this.rchtxt.Text = exc.Message + " #### " + exc.InnerException != null ? exc.InnerException.Message : string.Empty; } AdGroupService agService = (AdGroupService)User.GetService(AdWordsService.v201302.AdGroupService); ConstantDataService constData = (ConstantDataService)User.GetService(AdWordsService.v201302.ConstantDataService); Language[] lang = constData.getLanguageCriterion(); // Create the selector. Selector selector = new Selector(); selector.fields = new string[] { "Id", "Status", "Clicks" }; // Set the filters. // Predicate predicate = new Predicate(); // predicate.field = "CampaignId"; // predicate.@operator = PredicateOperator.EQUALS; // predicate.values = new string[] { campaignId.ToString() }; // selector.predicates = new Predicate[] { predicate }; // Set the selector paging. selector.paging = new Paging(); int offset = 0; int pageSize = 500; AdGroupPage page = new AdGroupPage(); try { do { selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; // Get all campaign targets. page = agService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (AdGroup adGroup in page.entries) { i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of ad groups criteria found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to get adgroup targeting criteria.", ex); } }
private void button2_Click(object sender, EventArgs e) { Dictionary <string, string> headers = new Dictionary <string, string>() { { "DeveloperToken", this.DeveloperToken.Text }, { "UserAgent", String.Format("Edge File Manager (version {0})", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()) }, { "EnableGzipCompression", this.EnableGzipCompression.Text }, { "ClientCustomerId", this.ClientCustomerId.Text }, { "Email", this.Email.Text } }; User = new AdWordsUser(headers); try { //Getting AuthToken (User.Config as AdWordsAppConfig).AuthToken = AdwordsUtill.GetAuthToken(User); } catch (Exception exc) { this.rchtxt.Text = exc.Message + " #### " + exc.InnerException != null ? exc.InnerException.Message : string.Empty; } CampaignCriterionService campaignCriterionService = (CampaignCriterionService)User.GetService(AdWordsService.v201302.CampaignCriterionService); // Create the selector. Selector selector = new Selector(); selector.fields = new string[] { "Id", "CriteriaType", "CampaignId" }; // Set the filters. // Predicate predicate = new Predicate(); // predicate.field = "CampaignId"; // predicate.@operator = PredicateOperator.EQUALS; // predicate.values = new string[] { campaignId.ToString() }; // selector.predicates = new Predicate[] { predicate }; // Set the selector paging. selector.paging = new Paging(); int offset = 0; int pageSize = 500; CampaignCriterionPage page = new CampaignCriterionPage(); try { do { selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; // Get all campaign targets. page = campaignCriterionService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (CampaignCriterion campaignCriterion in page.entries) { string negative = (campaignCriterion is NegativeCampaignCriterion) ? "Negative " : ""; Console.WriteLine("{0}) {1}Campaign criterion with id = '{2}' and Type = {3} was " + " found for campaign id '{4}'", i, negative, campaignCriterion.criterion.id, campaignCriterion.criterion.type, campaignCriterion.campaignId); i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of campaign targeting criteria found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to get campaign targeting criteria.", ex); } }
private void GetCampaigns_Click(object sender, EventArgs e) { Dictionary <string, string> headers = new Dictionary <string, string>() { { "DeveloperToken", this.DeveloperToken.Text }, { "UserAgent", String.Format("Edge File Manager (version {0})", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()) }, { "EnableGzipCompression", this.EnableGzipCompression.Text }, { "ClientCustomerId", this.ClientCustomerId.Text }, { "Email", this.Email.Text } }; User = new AdWordsUser(headers); try { //Getting AuthToken (User.Config as AdWordsAppConfig).AuthToken = AdwordsUtill.GetAuthToken(User); } catch (Exception exc) { this.rchtxt.Text = exc.Message + " #### " + exc.InnerException != null ? exc.InnerException.Message : string.Empty; } // Get the CampaignService. CampaignService campaignService = (CampaignService)User.GetService(AdWordsService.v201302.CampaignService); // Create the query. string query = "SELECT Id, Name, Status,Settings ORDER BY Name"; int offset = 0; int pageSize = 500; CampaignPage page = new CampaignPage(); try { do { string queryWithPaging = string.Format("{0} LIMIT {1}, {2}", query, offset, pageSize); // Get the campaigns. page = campaignService.query(queryWithPaging); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (Campaign campaign in page.entries) { this.rchtxt.AppendText(string.Format("/n Campaign id = '{0}', name = '{1}' ,status = '{2}'" + " was found.", campaign.id, campaign.name, campaign.status)); // i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to retrieve campaigns", ex); } }
private void GetAccountHierarchy_Click(object sender, EventArgs e) { Dictionary <string, string> headers = new Dictionary <string, string>() { { "DeveloperToken", this.DeveloperToken.Text }, { "UserAgent", String.Format("Edge File Manager (version {0})", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()) }, { "EnableGzipCompression", this.EnableGzipCompression.Text }, { "ClientCustomerId", this.ClientCustomerId.Text }, { "Email", this.Email.Text } }; User = new AdWordsUser(headers); try { //Getting AuthToken (User.Config as AdWordsAppConfig).AuthToken = AdwordsUtill.GetAuthToken(User); } catch (Exception exc) { this.rchtxt.Text = exc.Message + " #### " + exc.InnerException != null? exc.InnerException.Message:string.Empty; } // Get the ManagedCustomerService. ManagedCustomerService managedCustomerService = (ManagedCustomerService)User.GetService( AdWordsService.v201302.ManagedCustomerService); managedCustomerService.RequestHeader.clientCustomerId = null; // Create selector. Selector selector = new Selector(); selector.fields = new String[] { "Login", "CustomerId", "Name" }; try { // Get results. ManagedCustomerPage page = managedCustomerService.get(selector); // Display serviced account graph. if (page.entries != null) { // Create map from customerId to customer node. Dictionary <long, ManagedCustomerTreeNode> customerIdToCustomerNode = new Dictionary <long, ManagedCustomerTreeNode>(); // Create account tree nodes for each customer. foreach (ManagedCustomer customer in page.entries) { ManagedCustomerTreeNode node = new ManagedCustomerTreeNode(); node.Account = customer; customerIdToCustomerNode.Add(customer.customerId, node); } // For each link, connect nodes in tree. if (page.links != null) { foreach (ManagedCustomerLink link in page.links) { ManagedCustomerTreeNode managerNode = customerIdToCustomerNode[link.managerCustomerId]; ManagedCustomerTreeNode childNode = customerIdToCustomerNode[link.clientCustomerId]; childNode.ParentNode = managerNode; if (managerNode != null) { managerNode.ChildAccounts.Add(childNode); } } } // Find the root account node in the tree. ManagedCustomerTreeNode rootNode = null; foreach (ManagedCustomer account in page.entries) { if (customerIdToCustomerNode[account.customerId].ParentNode == null) { rootNode = customerIdToCustomerNode[account.customerId]; break; } } // Display account tree. rchtxt.AppendText("Login, CustomerId, Name"); rchtxt.AppendText(rootNode.ToTreeString(0, new StringBuilder())); // Console.WriteLine("Login, CustomerId, Name"); // Console.WriteLine(rootNode.ToTreeString(0, new StringBuilder())); } else { Console.WriteLine("No serviced accounts were found."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create ad groups.", ex); } }
private void GetAccountHistory_Click(object sender, EventArgs e) { Dictionary <string, string> headers = new Dictionary <string, string>() { { "DeveloperToken", this.DeveloperToken.Text }, { "UserAgent", String.Format("Edge File Manager (version {0})", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()) }, { "EnableGzipCompression", this.EnableGzipCompression.Text }, { "ClientCustomerId", this.ClientCustomerId.Text }, { "Email", this.Email.Text } }; User = new AdWordsUser(headers); try { //Getting AuthToken (User.Config as AdWordsAppConfig).AuthToken = AdwordsUtill.GetAuthToken(User); // Get the CustomerSyncService. CustomerSyncService customerSyncService = (CustomerSyncService)User.GetService(AdWordsService.v201302.CustomerSyncService); // The date time string should be of the form yyyyMMdd HHmmss zzz string minDateTime = DateTime.Now.AddDays(-1).ToUniversalTime().ToString("yyyyMMdd HHmmss") + " UTC"; string maxDateTime = DateTime.Now.ToUniversalTime().ToString("yyyyMMdd HHmmss") + " UTC"; // Create date time range. DateTimeRange dateTimeRange = new DateTimeRange(); dateTimeRange.min = minDateTime; dateTimeRange.max = maxDateTime; // Create the selector. CustomerSyncSelector selector = new CustomerSyncSelector(); selector.dateTimeRange = dateTimeRange; selector.campaignIds = GetAllCampaignIds(User); // Get all account changes for campaign. CustomerChangeData accountChanges = customerSyncService.get(selector); // Display the changes. if (accountChanges != null && accountChanges.changedCampaigns != null) { Console.WriteLine("Displaying changes up to: {0}", accountChanges.lastChangeTimestamp); foreach (CampaignChangeData campaignChanges in accountChanges.changedCampaigns) { Console.WriteLine("Campaign with id \"{0}\" was changed:", campaignChanges.campaignId); Console.WriteLine(" Campaign changed status: {0}", campaignChanges.campaignChangeStatus); if (campaignChanges.campaignChangeStatus != ChangeStatus.NEW) { Console.WriteLine(" Added ad extensions: {0}", GetFormattedList( campaignChanges.addedAdExtensions)); Console.WriteLine(" Added campaign criteria: {0}", GetFormattedList(campaignChanges.addedCampaignCriteria)); Console.WriteLine(" Added campaign targeting: {0}", campaignChanges.campaignTargetingChanged ? "yes" : "no"); Console.WriteLine(" Deleted ad extensions: {0}", GetFormattedList(campaignChanges.deletedAdExtensions)); Console.WriteLine(" Deleted campaign criteria: {0}", GetFormattedList(campaignChanges.deletedCampaignCriteria)); if (campaignChanges.changedAdGroups != null) { foreach (AdGroupChangeData adGroupChanges in campaignChanges.changedAdGroups) { Console.WriteLine(" Ad group with id \"{0}\" was changed:", adGroupChanges.adGroupId); Console.WriteLine(" Ad group changed status: {0}", adGroupChanges.adGroupChangeStatus); if (adGroupChanges.adGroupChangeStatus != ChangeStatus.NEW) { Console.WriteLine(" Ads changed: {0}", GetFormattedList(adGroupChanges.changedAds)); Console.WriteLine(" Criteria changed: {0}", GetFormattedList(adGroupChanges.changedCriteria)); Console.WriteLine(" Criteria deleted: {0}", GetFormattedList(adGroupChanges.deletedCriteria)); } } } } Console.WriteLine(); } } else { Console.WriteLine("No account changes were found.");; } } catch (Exception ex) { throw new System.ApplicationException("Failed to get account changes.", ex); } }