1

Google アナリティクス Web サイトからデータを正常に取得する実用的なソリューションがありました。しかし、404 エラーが発生し始め、読んだ後、Google がサービスの URL を変更したことがわかりました。私は適切に同じことをしましたが、今はエラーが発生しています:

無効な URI: URI の形式を判別できませんでした。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;

namespace FractalConnect
{
public class BaseData
{

    public IEnumerable<KeyValuePair<Dimension, string>> Dimensions { get; set; }
    public IEnumerable<KeyValuePair<Metric, string>> Metrics { get; set; }

    private const string PageViewReportUrl =
      "https://www.google.com/analytics/feeds/data?ids={0}&dimensions={1}&metrics={2}&start-date={3}&end-date={4}&sort={5}&max-results={6}";
    internal static string authenticationKey { get; set; }



    private static XDocument getXMLData(string tableID, IEnumerable<Dimension> dimensions,
        IEnumerable<Metric> metrics, DateTime from, DateTime to, Metric sort, SortDirection direction, int maxrecords)
    {
        XDocument doc = null;
        if (authenticationKey.Length > 0)
        {
            var dimension = new StringBuilder();
            for (var i = 0; i < dimensions.Count(); i++)
            {
                dimension.Append("ga:" + dimensions.ElementAt(i));
                if (i < dimensions.Count() - 1)
                    dimension.Append(",");
            }
            var metric = new StringBuilder();
            for (var i = 0; i < metrics.Count(); i++)
            {
                metric.Append("ga:" + metrics.ElementAt(i));
                if (i < metrics.Count() - 1)
                    metric.Append(",");
            }
            var sorter = "ga:" + sort;
            if (direction == SortDirection.Descending)
                sorter = "-" + sorter;
            var fromDate = from.ToString("yyyy-MM-dd");
            var toDate = to.ToString("yyyy-MM-dd");
            var header = new[] { "Authorization: GoogleLogin " + authenticationKey };
            var url = string.Format(PageViewReportUrl, "ga:" + tableID, dimension, metric, fromDate, toDate, sorter, maxrecords);

            doc = XDocument.Parse(HttpRequests.HttpGetRequest(url, header));
        }

        return doc;
    }


    public static IEnumerable<BaseData> GetBaseData(string tableID, IEnumerable<Dimension> dimensions,
        IEnumerable<Metric> metrics, DateTime from, DateTime to, Metric sort, SortDirection direction, int maxrecords)
    {
        IEnumerable<BaseData> data = null;
        XDocument xml = getXMLData(tableID, dimensions, metrics, from, to, sort, direction, maxrecords);
        if (xml != null)
        {
            XNamespace dxp = xml.Root.GetNamespaceOfPrefix("dxp");
            XNamespace dns = xml.Root.GetDefaultNamespace();
            data = xml.Root.Descendants(dns + "entry").Select(element => new BaseData
            {
                Dimensions =
                  new List<KeyValuePair<Dimension, string>>(
                  element.Elements(dxp + "dimension").Select(
                    dimensionElement =>
                    new KeyValuePair<Dimension, string>(
                      dimensionElement.Attribute("name").Value.Replace("ga:", "")
                      .ParseEnum<Dimension>(),
                      dimensionElement.Attribute("value").Value))),
                Metrics =
                  new List<KeyValuePair<Metric, string>>(
                  from metricElement in element.Elements(dxp + "metric")
                  select new KeyValuePair<Metric, string>(
                    metricElement.Attribute("name").Value.Replace("ga:", "")
                      .ParseEnum<Metric>(),
                    metricElement.Attribute("value").Value))
            });
        }
        return data;
    }

    public static XDocument GetProfilesData(string email, string pwd)
    {

        XDocument docAnalyticsData = null;

        if (authenticationKey.Length > 0)

        {
            var header = new[] { "Authorization: GoogleLogin " + authenticationKey };
            docAnalyticsData = XDocument.Parse(HttpRequests.HttpGetRequest("https://www.googleapis.com/analytics/v2.4/data?ids=ga:XXXX&dimensions=ga:date&metrics=ga:visits&start-date=2012-04-01&end-date=2012-04-02&key?", header));
        }
        return docAnalyticsData;
    }

}

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.IO;

namespace FractalConnect
{
public class GADataFetcher
{
    public string Email { get; set; }
    public string Password { get; set; }
    private string AuthenticationKey { get; set; }
    private const string AuthenticationUrl = "https//www.googleapis.com/analytics/v2,4/management/accounts?key=AIzaSyDGaZZnDrHNaUyMwQHE-KnEB0LYvi8wQtI";
    public GADataFetcher(string email, string password)
    {
        this.Email = email;
        this.Password = password;
        try
        {
            Authenticate();
            BaseData.authenticationKey = AuthenticationKey;
        }
        catch
        {
            throw;
        }
    }

    private void Authenticate()
    {
        string AuthenticationPost = string.Format("accountType=GOOGLE&Email={0}&Passwd={1}&service=analytics&source=xxx-xxx",
            this.Email, this.Password);

        this.AuthenticationKey = null;
        string result = HttpRequests.HttpPostRequest(AuthenticationUrl, AuthenticationPost);
        var tokens = result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var item in tokens)
        {
            if (item.StartsWith("Auth="))
                AuthenticationKey = item;
        }
    }


    static IEnumerable<GAProfile> GetProfiles<T>(XDocument xml)
    where T : GAProfile, new()
    {
        XNamespace dxp = xml.Root.GetNamespaceOfPrefix("dxp");
        XNamespace dns = xml.Root.GetDefaultNamespace();
        IEnumerable<GAProfile> profiles = null;
        profiles = xml.Root.Descendants(dns + "entry").Select(f => new GAProfile
        {
            AccountID = f.Elements(dxp + "property").Where(x => x.Attribute("name").Value == "ga:accountId").First().Attribute("value").Value,
            AccountName = f.Elements(dxp + "property").Where(x => x.Attribute("name").Value == "ga:accountName").First().Attribute("value").Value,
            ProfileID = f.Elements(dxp + "property").Where(x => x.Attribute("name").Value == "ga:profileId").First().Attribute("value").Value,
            WebPropertyID = f.Elements(dxp + "property").Where(x => x.Attribute("name").Value == "ga:webPropertyId").First().Attribute("value").Value,
            Currency = f.Elements(dxp + "property").Where(x => x.Attribute("name").Value == "ga:currency").First().Attribute("value").Value,
            TimeZone = f.Elements(dxp + "property").Where(x => x.Attribute("name").Value == "ga:timezone").First().Attribute("value").Value,
            TableID = f.Element(dxp + "tableId").Value,
            Updated = DateTime.Parse(f.Element(dns + "updated").Value),
            ID = f.Element(dns + "id").Value,
            Title = f.Element(dns + "title").Value
        });
        return profiles;
    }
    public IEnumerable<GAProfile> GetUserProfiles()
    {
        var xml = BaseData.GetProfilesData(Email, Password);
        return GetProfiles<GAProfile>(xml);
    }

    public IEnumerable<GAData> GetAnalytics(string tableID, DateTime from, DateTime to, int max, List<Dimension> dimensions, List<Metric> metrics, Metric sort, SortDirection order)
    {
        IEnumerable<BaseData> data = BaseData.GetBaseData(tableID, dimensions, metrics, from, to, sort, order, max);
        return data.Select(d => new GAData
        {
            Pageviews = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.pageviews).Value),
            Bounces = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.bounces).Value),
            Entrances = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.entrances).Value),
            Exits = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.exits).Value),
            NewVisits = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.newVisits).Value),
            TimeOnPage = Convert.ToDouble(d.Metrics.FirstOrDefault(met => met.Key == Metric.timeOnPage).Value),
            TimeOnSite = Convert.ToDouble(d.Metrics.FirstOrDefault(met => met.Key == Metric.timeOnSite).Value),
            Visitors = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.visits).Value),
            Visits = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.pageviews).Value),
            UniquePageviews = Convert.ToInt32(d.Metrics.FirstOrDefault(met => met.Key == Metric.uniquePageviews).Value),
            ExitPagePath = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.exitPagePath).Value,
            LandingPagePath = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.landingPagePath).Value,
            NextPagePath = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.nextPagePath).Value,
            PagePath = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.pagePath).Value,
            PageTitle = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.pageTitle).Value,
            PreviousPagePath = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.previousPagePath).Value,
            SecondPagePath = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.secondPagePath).Value,
            Browser = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.browser).Value,
            BrowserVersion = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.browserVersion).Value,
            City = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.city).Value,
            ConnectionSpeed = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.connectionSpeed).Value,
            Country = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.country).Value,
            Date = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.date).Value,
            DaysSinceLastVisit = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.daysSinceLastVisit).Value,
            Day = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.day).Value,
            FlashVersion = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.flashVersion).Value,
            Hostname = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.hostname).Value,
            IsMobile = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.isMobile).Value,
            Hour = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.hour).Value,
            JavaEnabled = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.javaEnabled).Value,
            Language = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.language).Value,
            Latitude = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.latitude).Value,
            Longitude = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.longitude).Value,
            Month = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.month).Value,
            NetworkDomain = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.networkDomain).Value,
            NetworkLocation = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.networkLocation).Value,
            OperatingSystem = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.operatingSystem).Value,
            OperatingSystemVersion = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.operatingSystemVersion).Value,
            PageDepth = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.pageDepth).Value,
            Region = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.region).Value,
            ScreenColors = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.screenColors).Value,
            ScreenResolution = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.screenResolution).Value,
            SubContinent = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.subContinent).Value,
            UserDefinedValue = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.userDefinedValue).Value,
            VisitCount = Convert.ToInt32(d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.visitCount).Value),
            VisitLength = Convert.ToInt32(d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.visitLength).Value),
            VisitorType = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.visitorType).Value,
            Week = Convert.ToInt32(d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.week).Value),
            Year = Convert.ToInt32(d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.year).Value),
            Source = d.Dimensions.FirstOrDefault(dim => dim.Key == Dimension.source).Value
        });
    }
}
public enum Dimension
{
    exitPagePath,
    landingPagePath,
    nextPagePath,
    pagePath,
    pageTitle,
    previousPagePath,
    secondPagePath,
    browser,
    browserVersion,
    city,
    connectionSpeed,
    country,
    date,
    daysSinceLastVisit,
    day,
    flashVersion,
    hostname,
    isMobile,
    hour,
    javaEnabled,
    language,
    latitude,
    longitude,
    month,
    networkDomain,
    networkLocation,
    operatingSystem,
    operatingSystemVersion,
    pageDepth,
    region,
    screenColors,
    screenResolution,
    subContinent,
    userDefinedValue,
    visitCount,
    visitLength,
    visitorType,
    week,
    year,
    source,

}
public enum Metric
{
    bounces,
    entrances,
    exits,
    newVisits,
    pageviews,
    timeOnPage,
    timeOnSite,
    visitors,
    visits,
    uniquePageviews
}

public enum SortDirection
{
    Ascending,
    Descending
}

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;
using System.IO;
/// <summary>
/// Summary description for HttpRequests
/// </summary>
public static class HttpRequests
{
public static string HttpPostRequest(string url, string post)
{
    var encoding = new ASCIIEncoding();
    byte[] data = encoding.GetBytes(post);
    WebRequest request = WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;
    Stream stream = request.GetRequestStream();
    stream.Write(data, 0, data.Length);
    stream.Close();
    WebResponse response = request.GetResponse();
    String result;
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        result = sr.ReadToEnd();
        sr.Close();
    }
    return result;
}


public static string HttpGetRequest(string url, string[] headers)
{
    String result;
    WebRequest request = WebRequest.Create(url);
    if (headers.Length > 0)
    {
        foreach (var header in headers)
        {
            request.Headers.Add(header);
        }
    }
    WebResponse response = request.GetResponse();
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        result = sr.ReadToEnd();
        sr.Close();
    }
    return result;
}

}

これらはエラーの原因となっているすべてのページのようです。この件に関するヘルプをいただければ幸いです。

4

0 に答える 0