/// <summary> /// constructor for webapplications. Obtain the token using the authsub /// helper methods /// </summary> /// <param name="token">Your authentication token</param> /// <returns></returns> public Application(string token) { GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("wise", Application.Name); authFactory.Token = token; Application.service = new SpreadsheetsService(authFactory.ApplicationName); Application.service.RequestFactory = authFactory; }
public void TokenTest() { string service = "TestValue"; // TODO: Initialize to an appropriate value string applicationName = "TestValue"; // TODO: Initialize to an appropriate value GAuthSubRequestFactory target = new GAuthSubRequestFactory(service, applicationName); // TODO: Initialize to an appropriate value string expected = "TestValue"; string actual; target.Token = expected; actual = target.Token; Assert.AreEqual(expected, actual); }
protected void SubmitVideo_ServerClick(object sender, EventArgs e) { if (String.IsNullOrEmpty(this.Title.Text) == false && String.IsNullOrEmpty(this.Description.Text) == false && String.IsNullOrEmpty(this.Category.SelectedValue) == false && String.IsNullOrEmpty(this.Keyword.Text) == false) { GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory(ServiceNames.YouTube, "TesterApp"); YouTubeService service = new YouTubeService(authFactory.ApplicationName, "ytapi-FrankMantek-TestaccountforGD-sjgv537n-0", "AI39si4v3E6oIYiI60ndCNDqnPP5lCqO28DSvvDPnQt-Mqia5uPz2e4E-gMSBVwHXwyn_LF1tWox4LyM-0YQd2o4i_3GcXxa2Q" ); authFactory.Token = HttpContext.Current.Session["token"] as string; service.RequestFactory = authFactory; try { YouTubeEntry entry = new YouTubeEntry(); entry.Media = new Google.GData.YouTube.MediaGroup(); entry.Media.Description = new MediaDescription(this.Description.Text); entry.Media.Title = new MediaTitle(this.Title.Text); entry.Media.Keywords = new MediaKeywords(this.Keyword.Text); // entry.Media.Categories MediaCategory category = new MediaCategory(this.Category.SelectedValue); category.Attributes["scheme"] = YouTubeService.DefaultCategory; entry.Media.Categories.Add(category); FormUploadToken token = service.FormUpload(entry); HttpContext.Current.Session["form_upload_url"] = token.Url; HttpContext.Current.Session["form_upload_token"] = token.Token; string page = "http://" + Request.ServerVariables["SERVER_NAME"]; if (Request.ServerVariables["SERVER_PORT"] != "80") { page += ":" + Request.ServerVariables["SERVER_PORT"]; } page += Request.ServerVariables["URL"]; HttpContext.Current.Session["form_upload_redirect"] = page; Response.Redirect("UploadVideo.aspx"); } catch (GDataRequestException gdre) { HttpWebResponse response = (HttpWebResponse)gdre.Response; } } }
/// <summary> /// if the service is using a Google Request Factory it will set the passed /// in token to the factory. NET CF does not support authsubtokens here /// </summary> /// <returns>string</returns> public void SetAuthenticationToken(string token) { GDataGAuthRequestFactory factory = this.factory as GDataGAuthRequestFactory; if (factory != null) { factory.GAuthToken = token; } else { GAuthSubRequestFactory f = this.factory as GAuthSubRequestFactory; if (f != null) { f.Token = token; } } }
private ActionResult ConfigView(Settings settings, Config model) { // Grab all of the available sites that the authorized account has access to var authFactory = new GAuthSubRequestFactory("analytics", ApplicationName) { Token = settings.SessionToken }; var analytics = new AnalyticsService(authFactory.ApplicationName) { RequestFactory = authFactory }; foreach (AccountEntry entry in analytics.Query(new AccountQuery()).Entries) { var account = entry.Properties.First(x => x.Name == "ga:accountName").Value; if (!model.Sites.ContainsKey(account)) model.Sites.Add(account, new Dictionary<string, string>()); model.Sites[account].Add(entry.ProfileId.Value, entry.Title.Text); } return View("Config", model); }
public ActionResult Analytics(int? duration) { CacheContext.InvalidateOn(TriggerFrom.Any<SiteSettings>()); var settings = _siteSettingsService.GetSettings(); if (string.IsNullOrEmpty(settings.AnalyticsToken)) { const string scope = "https://www.google.com/analytics/feeds/"; var next = Url.Absolute(Url.Admin().Home().AuthResponse()); var auth = new AnalyticsAuthorize { Url = AuthSubUtil.getRequestUrl(next, scope, false, true) }; return View("AnalyticsAuthorize", auth); } if (string.IsNullOrEmpty(settings.AnalyticsProfileId)) { var config = new AnalyticsConfig { Accounts = GetAccounts(settings), Profiles = GetProfiles(settings) }; return View("AnalyticsConfig", config); } duration = duration ?? 30; var model = new Analytics { Duration = duration.Value, Start = DateTime.Today.AddDays(-1 * duration.Value), End = DateTime.Now, Visits = new Dictionary<DateTime, int>(), PageViews = new Dictionary<string, int>(), PageTitles = new Dictionary<string, string>(), TopReferrers = new Dictionary<string, int>(), TopSearches = new Dictionary<string, int>() }; if (model.Start > model.End) { var tempDate = model.Start; model.Start = model.End; model.End = tempDate; } var profiles = GetProfiles(settings); var profile = profiles.SingleOrDefault(x => x.Id == settings.AnalyticsProfileId); if (profile == null) throw new Exception("Unable to find the specified analytics profile: " + settings.AnalyticsProfileId); model.Profile = profile; var authFactory = new GAuthSubRequestFactory("analytics", "MvcKickstart") { Token = settings.AnalyticsToken }; var analytics = new AnalyticsService(authFactory.ApplicationName) { RequestFactory = authFactory }; var profileId = "ga:" + settings.AnalyticsProfileId; // Get from All Visits var visits = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits", Dimensions = "ga:date", Sort = "ga:date" }; var count = 0; foreach (DataEntry entry in analytics.Query(visits).Entries) { var value = entry.Metrics.First().IntegerValue; model.Visits.Add(model.Start.AddDays(count++), value); } // Get Site Usage var siteUsage = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits,ga:pageviews,ga:percentNewVisits,ga:avgTimeOnSite,ga:entranceBounceRate,ga:exitRate,ga:pageviewsPerVisit,ga:avgPageLoadTime" }; var siteUsageResult = (DataEntry)analytics.Query(siteUsage).Entries.FirstOrDefault(); if (siteUsageResult != null) { foreach (var metric in siteUsageResult.Metrics) { switch (metric.Name) { case "ga:visits": model.TotalVisits = metric.IntegerValue; break; case "ga:pageviews": model.TotalPageViews = metric.IntegerValue; break; case "ga:percentNewVisits": model.PercentNewVisits = metric.FloatValue; break; case "ga:avgTimeOnSite": model.AverageTimeOnSite = TimeSpan.FromSeconds(metric.FloatValue); break; case "ga:entranceBounceRate": model.EntranceBounceRate = metric.FloatValue; break; case "ga:exitRate": model.PercentExitRate = metric.FloatValue; break; case "ga:pageviewsPerVisit": model.PageviewsPerVisit = metric.FloatValue; break; case "ga:avgPageLoadTime": model.AveragePageLoadTime = TimeSpan.FromSeconds(metric.FloatValue); break; } } } // Get Top Pages var topPages = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:pageviews", Dimensions = "ga:pagePath,ga:pageTitle", Sort = "-ga:pageviews", NumberToRetrieve = 20 }; foreach (DataEntry entry in analytics.Query(topPages).Entries) { var value = entry.Metrics.First().IntegerValue; var url = entry.Dimensions.Single(x => x.Name == "ga:pagePath").Value.ToLowerInvariant(); var title = entry.Dimensions.Single(x => x.Name == "ga:pageTitle").Value; if (!model.PageViews.ContainsKey(url)) model.PageViews.Add(url, 0); model.PageViews[url] += value; if (!model.PageTitles.ContainsKey(url)) model.PageTitles.Add(url, title); } // Get Top Referrers var topReferrers = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits", Dimensions = "ga:source,ga:medium", Sort = "-ga:visits", Filters = "ga:medium==referral", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topReferrers).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:source").Value.ToLowerInvariant(); model.TopReferrers.Add(source, visitCount); } // Get Top Searches var topSearches = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits", Dimensions = "ga:keyword", Sort = "-ga:visits", Filters = "ga:keyword!=(not set);ga:keyword!=(not provided)", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topSearches).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:keyword").Value.ToLowerInvariant(); model.TopSearches.Add(source, visitCount); } return View(model); }
////////////////////////////////////////////////////////////////////// /// <summary>default constructor</summary> ////////////////////////////////////////////////////////////////////// internal GAuthSubRequest(GDataRequestType type, Uri uriTarget, GAuthSubRequestFactory factory) : base(type, uriTarget, factory) { this.factory = factory; }
public ActionResult AnalyticsSummary() { var to = DateTime.Today.AddDays(-1); var from = to.AddDays(-30); var model = new AnalyticsSummary { Visits = new List<int>(), PageViews = new Dictionary<string, int>(), PageTitles = new Dictionary<string, string>(), TopReferrers = new Dictionary<string, int>(), TopSearches = new Dictionary<string, int>() }; var settings = RavenSession.Load<Settings>(Settings.DefaultId); var authFactory = new GAuthSubRequestFactory("analytics", ApplicationName) { Token = settings.SessionToken }; var analytics = new AnalyticsService(authFactory.ApplicationName) { RequestFactory = authFactory }; // Get from All Visits var visits = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits", Dimensions = "ga:date", Sort = "ga:date" }; foreach (DataEntry entry in analytics.Query(visits).Entries) { var value = entry.Metrics.First().IntegerValue; model.Visits.Add(value); } // Get Site Usage var siteUsage = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits,ga:pageviews,ga:percentNewVisits,ga:avgTimeOnSite,ga:entranceBounceRate,ga:exitRate,ga:pageviewsPerVisit,ga:avgPageLoadTime" }; var siteUsageResult = (DataEntry)analytics.Query(siteUsage).Entries.FirstOrDefault(); if (siteUsageResult != null) { foreach (var metric in siteUsageResult.Metrics) { switch (metric.Name) { case "ga:visits": model.TotalVisits = metric.IntegerValue; break; case "ga:pageviews": model.TotalPageViews = metric.IntegerValue; break; case "ga:percentNewVisits": model.PercentNewVisits = metric.FloatValue; break; case "ga:avgTimeOnSite": model.AverageTimeOnSite = TimeSpan.FromSeconds(metric.FloatValue); break; case "ga:entranceBounceRate": model.EntranceBounceRate = metric.FloatValue; break; case "ga:exitRate": model.PercentExitRate = metric.FloatValue; break; case "ga:pageviewsPerVisit": model.PageviewsPerVisit = metric.FloatValue; break; case "ga:avgPageLoadTime": model.AveragePageLoadTime = TimeSpan.FromSeconds(metric.FloatValue); break; } } } // Get Top Pages var topPages = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:pageviews", Dimensions = "ga:pagePath,ga:pageTitle", Sort = "-ga:pageviews", NumberToRetrieve = 20 }; foreach (DataEntry entry in analytics.Query(topPages).Entries) { var value = entry.Metrics.First().IntegerValue; var url = entry.Dimensions.Single(x => x.Name == "ga:pagePath").Value.ToLowerInvariant(); var title = entry.Dimensions.Single(x => x.Name == "ga:pageTitle").Value; if (!model.PageViews.ContainsKey(url)) model.PageViews.Add(url, 0); model.PageViews[url] += value; if (!model.PageTitles.ContainsKey(url)) model.PageTitles.Add(url, title); } // Get Top Referrers var topReferrers = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits", Dimensions = "ga:source,ga:medium", Sort = "-ga:visits", Filters = "ga:medium==referral", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topReferrers).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:source").Value.ToLowerInvariant(); model.TopReferrers.Add(source, visitCount); } // Get Top Searches var topSearches = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits", Dimensions = "ga:keyword", Sort = "-ga:visits", Filters = "ga:keyword!=(not set);ga:keyword!=(not provided)", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topSearches).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:keyword").Value.ToLowerInvariant(); model.TopSearches.Add(source, visitCount); } return View(model); }
static void Main(string[] args) { if (args.Length < 5) { Console.WriteLine("Not enough parameters. Usage is ExecRequest <service> <cmd> <uri> <username> <password>, where cmd is QUERY, UPDATE, INSERT, DELETE"); Console.WriteLine("or"); Console.WriteLine("ExecRequest <service> <cmd> <uri> /a <authsubtoken> - to use a session token"); Console.WriteLine("or"); Console.WriteLine("ExecRequest <service> <cmd> <uri> /e <authsubtoken> - to exchance a one time token for a session token"); return; } string s = args[0]; string cmd = args[1]; string targetUri = args[2]; string userName = args[3]; string passWord = args[4]; Service service = new Service(s, ApplicationName); if (userName.Equals("/a")) { Console.WriteLine("Using AuthSubToken: " + passWord); // password should contain the authsubtoken GAuthSubRequestFactory factory = new GAuthSubRequestFactory(s, ApplicationName); factory.Token = passWord; service.RequestFactory = factory; } else if (userName.Equals("/e")) { Console.WriteLine("Using Onetime token: " + passWord); passWord = AuthSubUtil.exchangeForSessionToken(passWord, null); Console.WriteLine("Exchanged for Session Token: " + passWord); // password should contain the authsubtoken GAuthSubRequestFactory factory = new GAuthSubRequestFactory(s, ApplicationName); factory.Token = passWord; service.RequestFactory = factory; } else { Console.WriteLine("Setting user credentials for: " + userName); service.setUserCredentials(userName, passWord); } try { if (cmd.Equals("QUERY")) { Console.WriteLine("Querying: " + targetUri); Stream result = service.Query(new Uri(targetUri)); DumpStream(result); } if (cmd.Equals("DELETE")) { service.Delete(new Uri(targetUri)); Console.WriteLine("successfully deleted: " + targetUri); } if (cmd.Equals("POST")) { String input = Console.In.ReadToEnd(); Console.Write(input); Stream result = service.StringSend(new Uri(targetUri), input, GDataRequestType.Insert); DumpStream(result); } if (cmd.Equals("UPDATE")) { String input = Console.In.ReadToEnd(); Console.Write(input); Stream result = service.StringSend(new Uri(targetUri), input, GDataRequestType.Update); DumpStream(result); } } catch (GDataRequestException e) { HttpWebResponse response = e.Response as HttpWebResponse; Console.WriteLine("Error executing request for Verb: " + cmd + ", Errorcode: " + response.StatusCode); Console.WriteLine(response.StatusDescription); Console.WriteLine(e.ResponseString); } }
public void PrivateKeyTest() { string service = "TestValue"; // TODO: Initialize to an appropriate value string applicationName = "TestValue"; // TODO: Initialize to an appropriate value GAuthSubRequestFactory target = new GAuthSubRequestFactory(service, applicationName); // TODO: Initialize to an appropriate value AsymmetricAlgorithm expected = new DSACryptoServiceProvider(); AsymmetricAlgorithm actual; target.PrivateKey = expected; actual = target.PrivateKey; Assert.AreEqual(expected, actual); }
private ActionResult OAuthCallback() { IAuthorizationState auth = client.ProcessUserAuthorization(Request); Session["auth"] = auth; var authFactory = new GAuthSubRequestFactory("cp", "Geeks Dilemma") {Token = auth.AccessToken}; var service = new ContactsService(authFactory.ApplicationName) {RequestFactory = authFactory}; var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); query.NumberToRetrieve = 1000; ContactsFeed contacts = service.Query(query); ViewBag.ImportFrom = "Google"; var userId = GetCurrentUserId(); DeletePreviousImportIfNecessary(userId); var googleContact = new GoogleContact { UserId = userId, Contacts = (from ContactEntry entry in contacts.Entries from email in entry.Emails where entry.Name != null where email != null select new ImportModel { Import = false, EmailAddress = email.Address.ToLower(), Name = entry.Name.FullName }).ToList() }; RavenSession.Store(googleContact); return View("Import"); }
static void Main(string[] args) { if (args.Length == 0) { ShowUsage(); return; } string pid = findValue(args, "pid", null); string pname = findValue(args, "pname", null); string authToken = findValue(args, "a", null); string exchangeToken = findValue(args, "e", null); string userName = findValue(args, "user", null); string passWord = findValue(args, "pwd", null); bool isRegister = isOption(args, "register", false); bool isInsert = isOption(args, "insert", false); bool isClean = isOption(args, "clean", false); bool isShow = isOption(args, "show", false); bool isList = isOption(args, "list", false); bool doCCR = isOption(args, "ccr", false); bool doSummary = isOption(args, "summary", false); if ((pid == null && pname == null && isList == false) && (exchangeToken == null && authToken == null)) { ShowUsage(); return; } HealthService service = new HealthService(ApplicationName); if (authToken != null) { Console.WriteLine("Using AuthSubToken: " + authToken); GAuthSubRequestFactory factory = new GAuthSubRequestFactory(HealthService.ServiceName, ApplicationName); factory.Token = authToken; service.RequestFactory = factory; } else if (exchangeToken != null) { Console.WriteLine("Using Onetime token: " + exchangeToken); authToken = AuthSubUtil.exchangeForSessionToken(exchangeToken, null); Console.WriteLine("Exchanged for Session Token: " + exchangeToken); GAuthSubRequestFactory factory = new GAuthSubRequestFactory(HealthService.ServiceName, ApplicationName); factory.Token = authToken; service.RequestFactory = factory; } else { Console.WriteLine("Setting user credentials for: " + userName); service.setUserCredentials(userName, passWord); } HealthQuery query; try { if (isList == true) { HealthFeed feed = service.Query(new HealthQuery(HealthQuery.ProfileListFeed)); Console.WriteLine ("Feed =" + feed); foreach (AtomEntry entry in feed.Entries) { Console.WriteLine("\tProfile " + entry.Title.Text + " has ID: " + entry.Content.Content); } return; } if (pid == null && pname != null) { // need to find the ID first. // so we get the list feed, find the name in the TITLE, and then // get the ID out of the content field HealthFeed feed = service.Query(new HealthQuery(HealthQuery.ProfileListFeed)); foreach (AtomEntry entry in feed.Entries) { if (entry.Title.Text == pname) { pid = entry.Content.Content; } } } if (authToken != null) { if (isRegister == true) { query = new HealthQuery(HealthQuery.AuthSubRegisterFeed); } else { query = new HealthQuery(HealthQuery.AuthSubProfileFeed); if (doSummary == true) { query.Digest = true; } } } else { if (isRegister == true) { query = HealthQuery.RegisterQueryForId(pid); } else { query = HealthQuery.ProfileQueryForId(pid); if (doSummary == true) { query.Grouped = true; query.GroupSize = 1; } } } Console.WriteLine("Resolved targetUri to: " + query.Uri.ToString()); if (doCCR == true) { HealthFeed feed = service.Query(query); foreach (HealthEntry e in feed.Entries ) { XmlNode ccr = e.CCR; if (ccr != null) { XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; ccr.WriteTo(writer); } } } else { if (isShow == true || doSummary == true) { Stream result = service.Query(query.Uri); DumpStream(result); } } if (isInsert == true) { String input = Console.In.ReadToEnd(); Console.Write(input); Stream result = service.StringSend(query.Uri, input, GDataRequestType.Insert); DumpStream(result); } if (isClean == true) { int count = 0; AtomFeed feed = service.Query(query); Console.WriteLine("Retrieved Feed, now deleting all entries in the feed"); foreach (AtomEntry entry in feed.Entries) { Console.WriteLine(".... deleting entry " + entry.Title.Text); entry.Delete(); count++; } Console.WriteLine("Deleted " + count + " entries"); } } catch (GDataRequestException e) { HttpWebResponse response = e.Response as HttpWebResponse; Console.WriteLine("Error executing request for Verb, Errorcode: " + response.StatusCode); Console.WriteLine(response.StatusDescription); Console.WriteLine(e.ResponseString); } }