2015-07-13 131 views
-1

//請幫助,使這個代碼可行錯誤請求錯誤

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

    namespace GoogleAnalyticsSupport 
    { 
    public class ReportRequestorWithSorting 
    { 
    #region Fields 

//I am getting bad request error 

     private static readonly string requestUrlFormat = "https://www.googleapis.com/analytics/v3/data?ids={1}&metrics={2}&sort={3}&start-date={4}&end-date={5}&start-index={6}&max-results={7}"; 
    private static readonly string authUrlFormat = "accountType=GOOGLE&Email={0}&Passwd={1}&source=reimers.dk-analyticsreader-0.1&service=analytics"; 
    private static CultureInfo ci = CultureInfo.GetCultureInfo("en-US"); 
    private string _token = null; 
    private string _username = null; 
    private string _password = null; 


    #endregion 

    #region Constructor 

    public ReportRequestorWithSorting() { } 

    public ReportRequestorWithSorting(string email, string password) 
    { 
    _username = email; 
    _password = password; 

    } 

    #endregion 

    #region Properties 

    public string Email 
    { 
    get { return _username; } 

    set 
    { 
    if (!string.Equals(_username, value)) 
    { 
    _username = value; 
    _token = null; 
    } 
    } 
    } 

    public string Password 
    { 
    get { return _password; } 
    set 
    { 
    if (!string.Equals(_password, value)) 
    { 
    _password = value; 
    _token = null; 
    } 
    } 
    } 

    #endregion 

    #region Methods 

\\struggling to replace the new authentication method\\ 

    private string GetToken(string username, string password) 
    { 
    if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password)) 
    { 
    throw new ArgumentNullException("Username, Password", "Username and/or password not set"); 
    } 

    string authBody = string.Format(authUrlFormat, username, password); 
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://accounts.google.com/o/oauth2/auth"); 
    req.Method = "POST"; 
    req.ContentType = "application/x-www-form-urlencoded"; 
    req.UserAgent = "Example.dk req"; 

    Stream stream = req.GetRequestStream(); 
    StreamWriter sw = new StreamWriter(stream); 
    sw.Write(authBody); 
    sw.Close(); 
    sw.Dispose(); 

    HttpWebResponse response = (HttpWebResponse)req.GetResponse(); 
    StreamReader sr = new StreamReader(response.GetResponseStream()); 
    string token = sr.ReadToEnd(); 
    string[] tokens = token.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); 

    foreach (string item in tokens) 
    { 
    if (item.StartsWith("Auth=")) 
    { 
    return item.Replace("Auth=", ""); 
    } 
    } 

    return string.Empty; 
    } 

    public IEnumerable<AnalyticsAccountInfo> GetAccounts() 
    { 
    if (string.IsNullOrEmpty(_token)) 
    { 
    _token = GetToken(_username, _password); 
    } 

    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.googleapis.com/analytics/v2.4/management/accounts"); 
    req.Headers.Add("Authorization: GoogleLogin auth=" + _token); 
    HttpWebResponse response = (HttpWebResponse)req.GetResponse(); 

    Stream responseStream = response.GetResponseStream(); 
    StreamReader sr = new StreamReader(responseStream); 
    string responseXml = sr.ReadToEnd(); 

    XDocument doc = XDocument.Parse(responseXml); 
    XNamespace dxpSpace = doc.Root.GetNamespaceOfPrefix("dxp"); 
    XNamespace defaultSpace = doc.Root.GetDefaultNamespace(); 

    var entries = from en in doc.Root.Descendants(defaultSpace + "entry") 
    select new AnalyticsAccountInfo 
    { 
    AccountID = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:accountId").First().Attribute("value").Value, 
    AccountName = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:accountName").First().Attribute("value").Value, 
    ID = en.Element(defaultSpace + "id").Value, 
    Title = en.Element(defaultSpace + "title").Value, 
    ProfileID = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:profileId").First().Attribute("value").Value, 
    WebPropertyID = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:webPropertyId").First().Attribute("value").Value 
    }; 

    return entries; 
    } 

    private XDocument getReport(AnalyticsAccountInfo account, IEnumerable<Dimension> dimensions, IEnumerable<Metric> metrics 
    , IEnumerable<Sort> sorts, DateTime from, DateTime to, int startindex = 1, int maxresults = 250) 
    { 
    if (string.IsNullOrEmpty(_token)) 
    { 
    _token = GetToken(_username, _password); 
    } 

    StringBuilder dims = new StringBuilder(); 

    foreach (Dimension item in dimensions) 
    { 
    dims.Append("ga:" + item.ToString() + ","); 
    } 

    StringBuilder mets = new StringBuilder(); 

    foreach (Metric item in metrics) 
    { 
    mets.Append("ga:" + item.ToString() + ","); 
    } 
    StringBuilder srt = new StringBuilder(); 

    foreach (Sort item in sorts) 
    { 
    srt.Append("-" + "ga:" + item.ToString() + ","); 
    } 
    string requestUrl = string.Format(requestUrlFormat, "ga:" + account.ProfileID, dims.ToString().Trim(",".ToCharArray()), mets.ToString().Trim(",".ToCharArray()) 
    , srt.ToString().Trim(",".ToCharArray()), from.ToString("yyyy-MM-dd"), to.ToString("yyyy-MM-dd"), startindex, maxresults); 

    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestUrl); 
    req.Headers.Add("Authorization: GoogleLogin auth=" + _token); 
    HttpWebResponse response = (HttpWebResponse)req.GetResponse(); 

    Stream responseStream = response.GetResponseStream(); 
    string responseXml = new StreamReader(responseStream, Encoding.UTF8, true).ReadToEnd(); 
    XDocument doc = XDocument.Parse(responseXml); 

    return doc; 
    } 


    public IEnumerable<GenericEntry> ReportRequestWF(AnalyticsAccountInfo account, IEnumerable<Dimension> dimensions, IEnumerable<Metric> metrics 
    , IEnumerable<Sort> sorts, DateTime from, DateTime to, int startindex = 1, int maxresults = 250) 
    { 
    XDocument doc = getReport(account, dimensions, metrics 
    , sorts, from, to, startindex, maxresults); 
    XNamespace dxpSpace = doc.Root.GetNamespaceOfPrefix("dxp"); 
    XNamespace defaultSpace = doc.Root.GetDefaultNamespace(); 

    var gr = from r in doc.Root.Descendants(defaultSpace + "entry") 
    select new GenericEntry 
    { 
    Dimensions = new List<KeyValuePair<Dimension, string>>(
    from rd in r.Elements(dxpSpace + "dimension") 
    select new KeyValuePair<Dimension, string>(
    (Dimension)Enum.Parse(
    typeof(Dimension), 
    rd.Attribute("name").Value.Replace("ga:", ""), 
    true), 
    rd.Attribute("value").Value)), 
    Metrics = new List<KeyValuePair<Metric, string>>(
    from rm in r.Elements(dxpSpace + "metric") 
    select new KeyValuePair<Metric, string>(
    (Metric)Enum.Parse(typeof(Metric), rm.Attribute("name").Value.Replace("ga:", ""), true), 
    rm.Attribute("value").Value)), 

    Sorts = new List<KeyValuePair<Sort, string>>(
    from rs in r.Elements(dxpSpace + "sort") 
    select new KeyValuePair<Sort, string>(
    (Sort)Enum.Parse(typeof(Sort), rs.Attribute("name").Value.Replace("ga:", ""), true), 
    rs.Attribute("value").Value)) 

    }; 

    return gr; 
    } 
    #endregion 
    } 
    } 

剛剛創建的通用,維度和指標類文件,在這裏叫他們。

回答

2

該代碼不起作用。您似乎嘗試通過客戶端登錄(登錄名和密碼)進行身份驗證Google關閉客戶端登錄2015年4月,您無法再使用客戶端登錄訪問Google API。

您將需要移動使用的oauth2或服務帳戶

Normaly我會建議使用.net client library但你似乎想在這個時候合併到SSIS這個.NET客戶端庫不強的名字簽署所以不會與ssis合作。您將不得不手動重新創建Oauth2流程。

有用的鏈接

+0

使用服務帳戶的方法解決 –