uwekeim icon

Retrieve daily costs through Google AdWords API v201309

uwekeim | PRO | 11/26/13 06:37:35 AM UTC | 0 ⭐ | 1055 👁️ | Never ⏰ | []
C# |

1.55 KB

|

None

|

0 👍

/

0 👎

// See http://stackoverflow.com/questions/20114242 for details.
 
private static decimal coreGetAdwordsSumInRange(DateTime start, DateTime end)
{
    var reportDefinition =
        new ReportDefinition
        {
            reportName = string.Format(@"Campaign performance report #{0}", DateTime.Now.Ticks),
            dateRangeType = ReportDefinitionDateRangeType.CUSTOM_DATE,
            reportType = ReportDefinitionReportType.CAMPAIGN_PERFORMANCE_REPORT,
            downloadFormat = DownloadFormat.XML,
            includeZeroImpressions = false,
            selector = new Selector
            {
                fields = new[] { @"Cost" },
                dateRange = new DateRange {min = start.ToString(@"yyyyMMdd"), max = end.ToString(@"yyyyMMdd")}
            }
        };
 
    // --
 
    var sum = decimal.Zero;
 
    var tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + @".xml");
    try
    {
        var utils = new ReportUtilities(new AdWordsUser()) { ReportVersion = @"v201309" };
        utils.DownloadClientReport(reportDefinition, true, tempFilePath);
 
        var doc = new XmlDocument();
        doc.Load(tempFilePath);
 
        var costNodes = doc.SelectNodes(@"/report/table/row/@cost");
        if (costNodes != null)
        {
            foreach (XmlNode costNode in costNodes)
            {
                var cost = Convert.ToDecimal(costNode.InnerText);
                sum += cost/1000000m;
            }
        }
    }
    finally
    {
        File.Delete(tempFilePath);
    }
 
    return sum;
}

Comments