protected bool nastanotPostoi() { bool postoi = false; Google.GData.Calendar.EventEntry novNastan = (Google.GData.Calendar.EventEntry)Session["novNastan"]; string calendarId = ddlKalendari.SelectedItem.Value; EventQuery evQuery = new EventQuery(); GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "FEITPortal"); authFactory.Token = (string)Session["sessionToken"]; myCalendarService.RequestFactory = authFactory; evQuery.Uri = new Uri("http://www.google.com/calendar/feeds/" + calendarId + "/private/full"); Google.GData.Calendar.EventFeed evFeed = myCalendarService.Query(evQuery) as Google.GData.Calendar.EventFeed; if (evFeed != null) { foreach (Google.GData.Calendar.EventEntry en in evFeed.Entries) { string[] newEventId = novNastan.Content.Content.Split(':'); string[] eventId = en.Content.Content.Split(':'); int novLength = newEventId.Length; int starLength = eventId.Length; if (eventId[starLength - 1] == newEventId[novLength - 1]) { postoi = true; break; } } } return(postoi); }
public void PrintDateMinQueryResults(ContactsRequest cr) { Service service = new ContactsService("EventManagement"); service.setUserCredentials("*****@*****.**", "Vandematram@123"); var token = service.QueryClientLoginToken(); service.SetAuthenticationToken(token); GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "EventManagement"); authFactory.Token = (String)token; // CalendarService service2 = new CalendarService(authFactory.ApplicationName); service.RequestFactory = authFactory; ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); // query.StartDate = new DateTime(2008, 1, 1); Feed <Contact> feed = cr.Get <Contact>(query); foreach (Contact contact in feed.Entries) { Console.WriteLine(contact.Name.FullName); Console.WriteLine("Updated on: " + contact.Updated.ToString()); } }
/// <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; }
/// <summary> /// Helper method to create either single-instance or recurring events. /// For simplicity, some values that might normally be passed as parameters /// (such as author name, email, etc.) are hard-coded. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="entryTitle">Title of the event to create.</param> /// <param name="recurData">Recurrence value for the event, or null for /// single-instance events.</param> /// <returns>The newly-created EventEntry on the calendar.</returns> public static Service GetService(string SessionToken) { GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "CalendarSampleApp"); authFactory.Token = SessionToken; Service service = new Service("cl", authFactory.ApplicationName); service.RequestFactory = authFactory; return(service); }
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); }
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); }
public static CalendarService GetCalendarService(GoogleTokenModel GoogleTokenModelObj) { GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "API Project"); authFactory.Token = GoogleTokenModelObj.Access_Token; authFactory.KeepAlive = true; CalendarService service = new CalendarService("cl"); service.RequestFactory = authFactory; return(service); }
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> /// get list of blogs /// </summary> /// <returns></returns> public ActionResult List() { var sd = repository.GetSubDomains().Where(x => x.id == subdomainid.Value).Single(); if (string.IsNullOrEmpty(sd.bloggerSessionKey)) { return(Json("No permission".ToJsonFail())); } var authFactory = new GAuthSubRequestFactory("blogger", "tradelr"); authFactory.Token = sd.bloggerSessionKey; var service = new Service(authFactory.ApplicationName); service.RequestFactory = authFactory; var query = new FeedQuery(); query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs"); AtomFeed feed = null; var blogs = new List <GoogleBlogData>(); try { feed = service.Query(query); foreach (AtomEntry entry in feed.Entries) { var blog = new GoogleBlogData(); blog.name = entry.Title.Text; blog.blogHref = entry.AlternateUri.Content; foreach (AtomLink t in entry.Links) { if (t.Rel.Equals("http://schemas.google.com/g/2005#post")) { blog.blogUri = t.AbsoluteUri; } } blogs.Add(blog); } } catch (Exception ex) { Syslog.Write(ex); return(Json("No blogs found".ToJsonFail())); } var view = this.RenderViewToString("~/Areas/dashboard/Views/blogger/list.ascx", blogs); return(Json(view.ToJsonOKData())); }
public GoogleBlogExporter(string sessionKey, string hostName, ITradelrRepository repository, long sesssionid) { var authFactory = new GAuthSubRequestFactory("blogger", "tradelr") { Token = sessionKey }; service = new Service(authFactory.ApplicationName) { RequestFactory = authFactory }; this.hostName = hostName; this.repository = repository; this.ownerid = sesssionid; blogEntry = new AtomEntry(); }
protected void btnDodadi_Click(object sender, EventArgs e) { if (!nastanotPostoi()) { novNastan = (Google.GData.Calendar.EventEntry)Session["novNastan"]; string calendarId = ddlKalendari.SelectedItem.Value; GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "FEITPortal"); authFactory.Token = (string)Session["sessionToken"]; myCalendarService.RequestFactory = authFactory; Uri postUri = new Uri("http://www.google.com/calendar/feeds/" + calendarId + "/private/full"); AtomEntry insertedEntry = myCalendarService.Insert(postUri, novNastan); lblUspesno.Text = "Настанот беше успешно креиран!"; mwGoogleEvent.ActiveViewIndex = 2; } else { btnNazad.Visible = true; lblGreska.Text = "Настанот веќе постои во избраниот календар. Избришете го или обидете друг календар"; mwGoogleEvent.ActiveViewIndex = 3; } }
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 GoogleBaseExporter(long subdomainid, string hostname, long? sessionid = null) : this(hostname) { ownerid = sessionid; service = new ContentForShoppingService("tradelr"); var authFactory = new GAuthSubRequestFactory("gbase", "tradelr"); using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); if (sd.gbaseid.HasValue && !string.IsNullOrEmpty(sd.googleBase.sessiontoken)) { service.RequestFactory = authFactory; service.SetAuthenticationToken(sd.googleBase.sessiontoken); accountid = sd.googleBase.accountid.ToString(); } else { // use tradelr as default service.setUserCredentials("*****@*****.**", "tuaki1976"); accountid = "8812401"; } // get feed if (sd.gbaseid.HasValue) { var query = new ProductQuery("schema", accountid); feed = service.Query(query); InitLocalisation(sd.gbaseid.HasValue ? sd.googleBase.country : COUNTRY_US, sd.currency.ToCurrency()); } } }
private List <Friend> GetGmailContacts(int page, List <int> selectedIndexs) { int pageSize = 10; List <Friend> friends = new List <Friend>(); MembershipUser mu = Membership.GetUser(); RegisteredUser user = registeredUserRepository.GetByMembershipId(Convert.ToInt32(mu.ProviderUserKey)); if (Session["GMailToken"] == null) { String token = Request.QueryString["token"]; Session["GMailToken"] = AuthSubUtil.exchangeForSessionToken(token, null).ToString(); } GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cp", "testingFADE"); RequestSettings rs = new RequestSettings("testingFADE", (String)Session["GMailToken"]); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed <Contact> contacts = cr.GetContacts(); int i = 1; if (page > 0) { foreach (Contact e in contacts.Entries) { if (i < (page * pageSize) - 9) { i++; continue; } if (i > (page * pageSize)) { break; } if (e.PrimaryEmail == null) { continue; } Friend friend = new Friend(); friend.FirstName = e.Title; friend.EmailAddress = e.PrimaryEmail.Address; friend.InvitedBy = user; friends.Add(friend); i++; } ViewData["Pages"] = Common.Paging(contacts.TotalResults, page, pageSize, 10); } else if (selectedIndexs != null) { foreach (Contact e in contacts.Entries) { if (!selectedIndexs.Exists(delegate(int record) { if (record == i) { return(true); } return(false); })) { i++; continue; } Friend friend = new Friend(); friend.FirstName = e.Title; friend.EmailAddress = e.PrimaryEmail.Address; friend.InvitedBy = user; friends.Add(friend); i++; } } return(friends); }
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); } }
private IList <IContact> GetContacts(int pageNumber, int pageSize, ISelection selection) { IList <IContact> result = new List <IContact>(); GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cp", applicationName); authFactory.Token = this.token.ToString(); authFactory.PrivateKey = getRsaKey(); RequestSettings rs = new RequestSettings(applicationName, token.ToString()); rs.AutoPaging = true; ContactsService cs = new ContactsService(applicationName); cs.RequestFactory = authFactory; ContactsRequest cr = new ContactsRequest(rs); cr.Service = cs; Feed <Google.Contacts.Contact> contacts = cr.GetContacts(); int i = 1; if (pageNumber > 0) { foreach (Google.Contacts.Contact e in contacts.Entries) { if (i < (pageNumber * pageSize) - (pageSize - 1)) { i++; continue; } if (i > (pageNumber * pageSize)) { break; } GetContact(i++, result, e); } this.totalCount = contacts.TotalResults; } else if (selection != null) { foreach (Google.Contacts.Contact e in contacts.Entries) { if (!selection.SelectedAll && !selection.SelectedIndexs.Exists(delegate(int record) { if (record == i) { return(true); } return(false); })) { i++; continue; } if (selection.SelectedAll && selection.SelectedIndexs.Exists(delegate(int record) { if (record == i) { return(true); } return(false); })) { i++; continue; } if (e.PrimaryEmail == null) { continue; } Contact contact = new Contact(); contact.Index = i; contact.FirstName = e.Title; contact.Email = e.PrimaryEmail.Address; result.Add(contact); i++; } } else { foreach (Google.Contacts.Contact e in contacts.Entries) { GetContact(i++, result, e); } this.totalCount = contacts.TotalResults; } return(result); }
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.AnalyticsWidget().AuthResponse()); var auth = new Authorize { Url = AuthSubUtil.getRequestUrl(next, scope, false, true) }; return(View("AnalyticsAuthorize", auth)); } if (string.IsNullOrEmpty(settings.AnalyticsProfileId)) { var config = new Config { Accounts = GetAccounts(settings), Profiles = GetProfiles(settings) }; return(View("AnalyticsConfig", config)); } duration = duration ?? 30; var model = new ViewModels.Widgets.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)); }
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); } }
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)); }
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { string[] uris; string povtoruvanje = ""; mwGoogleEvent.ActiveViewIndex = 0; if ((Request.QueryString["token"] != null) && Session["sessionToken"] == null) { Session["sessionToken"] = AuthSubUtil.exchangeForSessionToken(Request.QueryString["token"], null); } GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "FEITPortal"); authFactory.Token = (string)Session["sessionToken"]; myCalendarService.RequestFactory = authFactory; CalendarQuery query = new CalendarQuery(); query.Uri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full"); try { CalendarFeed resultFeed = myCalendarService.Query(query); foreach (CalendarEntry entry in resultFeed.Entries) { uris = entry.Id.Uri.ToString().Split('/'); ListItem li = new ListItem(); li.Text = entry.Title.Text; li.Value = uris[8]; ddlKalendari.Items.Add(li); } } catch (Exception ex) { hlGcal1.Visible = true; hlNazad1.Visible = true; lblGreska.Text = "Немате креирано Google Calendar"; mwGoogleEvent.ActiveViewIndex = 3; } Calendar.COURSE_EVENTS_INSTANCEDataTable nastan = (Calendar.COURSE_EVENTS_INSTANCEDataTable)Session["gNastan"]; foreach (Calendar.COURSE_EVENTS_INSTANCERow r in nastan) { CoursesTier CourseTier = new CoursesTier(Convert.ToInt32(Session["COURSE_ID"])); novNastan.Content.Language = r.COURSE_EVENT_ID.ToString(); novNastan.Title.Text = r.TITLE; novNastan.Content.Content = "Предмет: " + CourseTier.Name + " Опис: " + r.DESCRIPTION + " Тип: " + r.TYPEDESCRIPTION + " ID:" + r.COURSE_EVENT_ID.ToString(); Where mesto = new Where(); mesto.ValueString = r.ROOM; novNastan.Locations.Add(mesto); int recType = Convert.ToInt32(r.RECURRENCE_TYPE); DateTime startDate = Convert.ToDateTime(r.STARTDATE); DateTime endDate = Convert.ToDateTime(r.ENDDATE); DateTime startTime = Convert.ToDateTime(r.STARTIME); DateTime endTime = Convert.ToDateTime(r.ENDTIME); TimeSpan span = endTime - startTime; if (recType != 0) { Recurrence rec = new Recurrence(); string recData; string dStart = "DTSTART;TZID=" + System.TimeZone.CurrentTimeZone.StandardName + ":" + startDate.ToString("yyyyMMddT") + startTime.AddHours(-1).ToString("HHmm") + "00\r\n"; string dEnd = "DTEND;TZID=" + System.TimeZone.CurrentTimeZone.StandardName + ":" + startDate.ToString("yyyyMMddT") + startTime.AddHours(-1 + span.Hours).ToString("HHmm") + "00\r\n"; string rRule = ""; povtoruvanje = "<b>Повторување:</b> "; switch (recType) { case 1: rRule = "RRULE:FREQ=DAILY;INTERVAL=" + r.RECURRENCE_NUMBER + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n"; povtoruvanje += "Дневно, секој " + r.RECURRENCE_NUMBER.ToString() + " ден <br> </br> <br> </br>"; break; case 2: string daysInWeek = ""; string denovi = ""; if (r.DAYSINWEEK[0] == '1') { daysInWeek += "MO,"; denovi += " Понеделник,"; } if (r.DAYSINWEEK[1] == '1') { daysInWeek += "TU,"; denovi += " Вторник,"; } if (r.DAYSINWEEK[2] == '1') { daysInWeek += "WE,"; denovi += " Среда,"; } if (r.DAYSINWEEK[3] == '1') { daysInWeek += "TH,"; denovi += " Четврток,"; } if (r.DAYSINWEEK[4] == '1') { daysInWeek += "FR,"; denovi += " Петок,"; } if (r.DAYSINWEEK[5] == '1') { daysInWeek += "SA,"; denovi += " Сабота,"; } if (r.DAYSINWEEK[6] == '1') { daysInWeek += "SU,"; denovi += " Недела,"; } daysInWeek = daysInWeek.Substring(0, daysInWeek.Length - 1); denovi = denovi.Substring(0, denovi.Length - 1); rRule = "RRULE:FREQ=WEEKLY;INTERVAL=" + r.RECURRENCE_NUMBER + ";BYDAY=" + daysInWeek + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n"; povtoruvanje += "Неделно, секоја " + r.RECURRENCE_NUMBER + " недела и тоа во: " + denovi + " <br> </br> <br> </br>"; break; case 3: rRule = "RRULE:FREQ=MONTHLY;INTERVAL=" + r.RECURRENCE_NUMBER + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n"; povtoruvanje += "Месечно, секој " + r.RECURRENCE_NUMBER + " месец <br> </br> <br> </br>"; break; } recData = dStart + dEnd + rRule; rec.Value = recData; novNastan.Recurrence = rec; } else { When vreme = new When(); vreme.StartTime = r.STARTIME; vreme.EndTime = r.ENDTIME; novNastan.Times.Add(vreme); } lblPrikaz.Text += "<b>Наслов: </b>" + r.TITLE + "<br> </br> <br> </br>"; lblPrikaz.Text += "<b>Опис: </b>" + r.DESCRIPTION + "<br> </br> <br> </br>"; lblPrikaz.Text += "<b>Просторија: </b>" + r.ROOM + "<br> </br> <br> </br>"; lblPrikaz.Text += "<b>Тип: </b>" + r.TYPEDESCRIPTION + "<br> </br> <br> </br>"; lblPrikaz.Text += povtoruvanje; lblPrikaz.Text += "<b>Почетен датум: </b>" + startDate.ToShortDateString() + " <b>Краен датум: </b>" + endDate.ToShortDateString() + "<br> </br> <br> </br>"; lblPrikaz.Text += "<b>Време: Од </b>" + startTime.ToShortTimeString() + " <b>До</b> " + endTime.ToShortTimeString(); } Session["novNastan"] = novNastan; } }
public ActionResult Import(string type, string token) { var owner = db.GetUserById(sessionid.Value, subdomainid.Value); var viewdata = new ImportContactsViewData(baseviewmodel) { hostName = accountHostname, fbuid = owner.FBID, subdomainid = subdomainid.Value, appid = sessionid.Value }; // facebook var connectSession = UtilFacebook.GetConnectSession(); if (connectSession.IsConnected()) { var api = new Api(connectSession); IList <long> fdlist = api.Friends.GetAppUsers(); string s = string.Empty; for (int i = 0; i < fdlist.Count; i++) { s += fdlist[i].ToString(); if (i != fdlist.Count - 1) { s += ","; } } viewdata.invitedFbuidList = s; } // if callback from authsub authorisation if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(token)) { var importType = type.ToEnum <ContactImportType>(); switch (importType) { case ContactImportType.GOOGLE: var requestFactory = new GAuthSubRequestFactory("cp", "tradelr"); requestFactory.Token = token; var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); //query.OAuthRequestorId = string.Concat(sessionid.Value, '@', subdomainid.Value); var service = new ContactsService(requestFactory.ApplicationName); service.RequestFactory = requestFactory; try { var feed = service.Query(query); var contacts = new List <ContactBasic>(); foreach (ContactEntry entry in feed.Entries) { string email; // primary email can be null if (entry.PrimaryEmail == null) { if (entry.Emails == null || entry.Emails.Count == 0) { continue; // skip entry, cannot find email } email = entry.Emails[0].Address; } else { email = entry.PrimaryEmail.Address; } var contact = new ContactBasic() { address = entry.BillingInformation, companyName = email, email = email }; if (entry.Name != null) { if (!string.IsNullOrEmpty(entry.Name.GivenName)) { contact.firstName = entry.Name.GivenName; } if (!string.IsNullOrEmpty(entry.Name.FamilyName)) { contact.lastName = entry.Name.FamilyName; } } if (entry.PrimaryPhonenumber == null) { if (entry.Phonenumbers != null && entry.Phonenumbers.Count != 0) { contact.phone = entry.Phonenumbers[0].Value; } } else { contact.phone = entry.PrimaryPhonenumber.Value; } // now we need to format it nicely for display purposes contacts.Add(contact); } viewdata.contacts = contacts.OrderBy(x => x.email); } catch (Exception ex) { Syslog.Write(ex); } break; default: break; } } return(View(viewdata)); }