protected void SetLinks(AtomEntry e) { LogService.Debug("AnnotateService.SetLinks entryId={0}", e.Id); var links = e.Links.ToList(); var url = new UrlHelper(Container.GetInstance<RequestContext>()); //atom threading extension if (e.InReplyTo != null) { e.InReplyTo.Href = url.RouteIdUri("AtomPubResource", e.InReplyTo.Ref, AbsoluteMode.Force); links.Merge(new AtomLink { Rel = "related", Type = "text/html", Href = url.RouteIdUri("AtomPubResource", e.InReplyTo.Ref, AbsoluteMode.Force) }); } //atom threading extension links.Merge(new AtomLink { Href = url.RouteIdUri("AnnotateEntryAnnotationsFeed", e.Id, AbsoluteMode.Force), Rel = "replies", Type = Atom.ContentType, Count = e.Total, Updated = DateTimeOffset.UtcNow }); e.Links = links; }
public void ContentIsCorrect( [Frozen]XmlAtomContent expected, AtomEntry sut) { XmlAtomContent actual = sut.Content; Assert.Equal(expected, actual); }
public virtual ActionResult AnnotateEntry(string workspace, string collection, int? year, int? month, int? day, string path) { if (HttpContext.Request.ContentType.ToUpper().StartsWith(Atom.ContentType.ToUpper())) { AtomEntry entry = new AtomEntry(); //note: don't dispose of incoming stream or it will close the response, still true? XmlReader reader = new XmlTextReader(HttpContext.Request.InputStream); entry.Xml = XElement.Load(reader); Id id = Collection.Id.AddPath(year, month, day, path); entry = AnnotateService.Annotate(id, entry, GetSlug()); return new XmlWriterResult((w) => entry.Xml.WriteTo(w)) { StatusCode = HttpStatusCode.Created, ContentType = Atom.ContentTypeEntry, ETag = AtomPubService.GetEntryEtag(entry.Id), Location = entry.Location, ContentLocation = entry.Location }; } else //media annotation { throw new NotImplementedException(); } }
public void LinksIsCorrect( [Frozen]IEnumerable<AtomLink> expected, AtomEntry sut) { IEnumerable<AtomLink> actual = sut.Links; Assert.Equal(expected, actual); }
public static void AssertEntriesEqual(AtomEntry entry, AtomEntry testEntry) { Assert.AreEqual(entry.Id.ToString(), testEntry.Id.ToString()); Assert.AreEqual(entry.Title.Text, testEntry.Title.Text); Assert.AreEqual(entry.Title.Lang, testEntry.Title.Lang); Assert.AreEqual(entry.Text.Text, testEntry.Text.Text); Assert.AreEqual(entry.Text.Lang, testEntry.Text.Lang); Assert.AreEqual(entry.Published.HasValue, testEntry.Published.HasValue, "Published"); if (entry.Published.HasValue) { AssertDatesApproximatelyEqual(entry.Published.Value, testEntry.Published.Value); } Assert.AreEqual(entry.Edited.HasValue, testEntry.Edited.HasValue, "Edited"); if (entry.Edited.HasValue) { AssertDatesApproximatelyEqual(entry.Edited.Value, testEntry.Edited.Value); } AssertDatesApproximatelyEqual(entry.Updated, testEntry.Updated); }
public virtual void AutoPing(AtomEntry entry) { LogService.Info("TrackbackService.AutoPing entryId={0}", entry.Id); //TODO: work in separate thread (use background worker or not?) if (!entry.Visible) { LogService.Info("Entry is not visible, AutoPing cancelled."); return; } if (!IsEnabled(entry)) { LogService.Info("Annotations and/or trackbacks are disabled, AutoPing cancelled."); return; } IEnumerable<Uri> links = entry.Content.Type != "xhtml" ? WebHelper.ExtractLinks(HttpUtility.HtmlDecode(entry.Content.Xml.ToString())) : WebHelper.ExtractLinks(entry.Content.Text); foreach (Uri link in links) { try { string page = null; Uri pingbackUrl = null; //go ahead and download page using (WebClient client = new WebClient()) { page = client.DownloadString(link); if (client.Headers["X-Pingback"] != null) pingbackUrl = new Uri(client.Headers["X-Pingback"]); } //try a trackback first since it supports title's and excerpts Uri trackbackUrl = DiscoverTrackbackPingUrl(page, link); if (trackbackUrl != null) { if (!SendTrackback(entry, trackbackUrl).Error) continue; //success, so move on to next link } //next try a pingback if (pingbackUrl == null) pingbackUrl = DiscoverPingbackLink(page); if (pingbackUrl != null) { if (!SendPingback(entry, pingbackUrl, link).FaultCode.HasValue) continue; //success } } catch (Exception ex) { LogService.Error("Failed to complete ping to link {0}", link.ToString()); LogService.Error(ex); } } }
public void DeleteMedia(AtomEntry mediaLinkEntry) { //TODO: transaction atomEntryRepository.DeleteEntry(mediaLinkEntry.Id); string path = pathResolver.GetMediaPath(mediaLinkEntry.Id, mediaLinkEntry.Content.Type); //TODO: resource not found exception System.IO.File.Delete(path); AtomSite.Utils.FileHelper.RemoveEmptyPaths(pathResolver.GetCollectionPath(mediaLinkEntry.Id), true); }
public AtomEntry UpdateMedia(AtomEntry mediaLinkEntry, Stream stream) { //TODO: transaction atomEntryRepository.UpdateEntry(mediaLinkEntry); string path = pathResolver.GetMediaPath(mediaLinkEntry.Id, mediaLinkEntry.Content.Type); //TODO: resource not found exception FileHelper.WriteStream(stream, path); return mediaLinkEntry; }
public void CreateAtomEntryWithIdTest() { AtomEntry atomEntry = new AtomEntry { Id = "tag:[email protected],2008:collection,entry" }; Assert.IsNotNull(atomEntry); Assert.IsNotNull(atomEntry.Id); }
protected virtual bool IsEnabled(AtomEntry entry) { BlogAppCollection coll = new BlogAppCollection(AppService.GetCollection(entry.Id)); if (!coll.AnnotationsOn) return false; //in case they got turned off if (!coll.TrackbacksOn) return false; if (!entry.AllowAnnotate) return false; //TODO: check expired return true; }
public void AddLinkReturnsCorrectResult( AtomEntry sut, AtomLink newLink) { AtomEntry actual = sut.AddLink(newLink); var expected = sut.AsSource().OfLikeness<AtomEntry>() .With(x => x.Links).EqualsWhen( (s, d) => sut.Links.Concat(new[] { newLink }).SequenceEqual(d.Links)); expected.ShouldEqual(actual); }
public static async Task<AtomEntry> ReadEntry(string path) { using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { var reader = XmlReader.Create(stream, TestAtomFeed.XmlReaderSettings); var entry = new AtomEntry(); await entry.ReadXmlAsync(reader); return entry; } }
public Stream GetMedia(AtomEntry mediaLinkEntry) { string path = pathResolver.GetMediaPath(mediaLinkEntry.Id, mediaLinkEntry.Content.Type); try { return System.IO.File.OpenRead(path); } catch (FileNotFoundException) { throw new ResourceNotFoundException("media", mediaLinkEntry.Id.ToString()); } }
public void CreateAtomEntryWithTitleTest() { AtomEntry atomEntry = new AtomEntry { Title = new AtomTitle { Text = "aTitle" } }; Assert.IsNotNull(atomEntry); Assert.IsNotNull(atomEntry.Title); }
public void CreateAtomEntryWithRightsTest() { AtomEntry atomEntry = new AtomEntry { Rights = new AtomRights { Text = "aRights" }, }; Assert.IsNotNull(atomEntry); Assert.IsNotNull(atomEntry.Rights); }
public void CreateAtomEntryWithSummaryTest() { AtomEntry atomEntry = new AtomEntry { Summary = new AtomSummary { Text = "aSummary" } }; Assert.IsNotNull(atomEntry); Assert.IsNotNull(atomEntry.Summary); }
public string GetMediaEtag(AtomEntry mediaLinkEntry) { string path = pathResolver.GetMediaPath(mediaLinkEntry.Id, mediaLinkEntry.Content.Type); try { //contentLength = (int)(new FileInfo(path).Length); return FileHelper.ComputeMD5Sum(path); } catch (FileNotFoundException) { throw new ResourceNotFoundException("media", mediaLinkEntry.Id.ToString()); } }
private void SetLinks(AtomEntry e) { var list = e.Links.ToList(); //if (e.Approved) list.Merge(new AtomLink() { Rel = "admin-approve", Href = RouteService.RouteUrl("AdminRoute", new { controller = "Admin", action = "EditEntry" }) }); //else list.Merge(new AtomLink() { Rel = "admin-approve", Href = RouteService.RouteUrl("AdminRoute", new { controller = "Admin", action = "EditEntry" }) }); if (AuthorizeService.IsAuthorized(GetUser(), e.Id.ToScope(), AuthAction.DeleteEntryOrMedia)) { list.Merge(new AtomLink() { Rel = "delete", Href = RouteService.RouteUrl("AtomPubEntryEdit", e.Id, AbsoluteMode.Force) }); } list.Merge(new AtomLink() { Rel = "admin-edit", Href = RouteService.RouteUrl(e.Media?"AdminEditMedia":"AdminEditEntry", new { id = e.Id.ToString() }, AbsoluteMode.Force) }); e.Links = list; }
protected void SetLinks(AtomEntry e) { if (!new BlogAppCollection(AppService.GetCollection(e.Id)).BloggingOn) return; LogService.Debug("BlogService.SetLinks entryId={0}", e.Id); var links = e.Links.ToList(); var url = new UrlHelper(Container.GetInstance<RequestContext>()); if (e.InReplyTo == null) { links.Merge(new AtomLink() { Rel = "alternate", Type = "text/html", Href = url.RouteIdUri("BlogEntry", e.Id, AbsoluteMode.Force) }); } else // annotation { links.Merge(new AtomLink() { Rel = "alternate", Type = "text/html", Href = new System.Uri(url.RouteIdUri("BlogEntry", e.InReplyTo.Ref, AbsoluteMode.Force).ToString() + "#" + e.Id.ToWebId()) }); e.InReplyTo.Href = url.RouteIdUri("BlogEntry", e.InReplyTo.Ref, AbsoluteMode.Force); links.Merge(new AtomLink { Rel = "related", Type = "text/html", Href = url.RouteIdUri("BlogEntry", e.InReplyTo.Ref, AbsoluteMode.Force) }); if (AnnotateService.GetAnnotationState(AppService.GetCollection(e.Id), e.Id) == AnnotationState.On) { links.Merge(new AtomLink { Rel = "reply", Type = "text/html", Href = new System.Uri(url.RouteIdUri("BlogEntry", e.InReplyTo.Ref, AbsoluteMode.Force).ToString() + "#addcommentform") }); } } e.Links = links; }
public AtomEntry CreateMedia(AtomEntry entry, Stream stream) { //TODO: transaction string path = pathResolver.GetMediaLinkEntryPath(entry.Id); Id id = entry.Id; int i = 1; while (System.IO.File.Exists(path)) { id = new Id(id.Owner, id.Date, id.Collection, entry.Id.EntryPath + i++); path = pathResolver.GetEntryPath(id); } entry.Id = id; path = pathResolver.GetMediaPath(entry.Id, entry.Content.Type); FileHelper.WriteStream(stream, path); //create & return the media link entry return atomEntryRepository.CreateEntry(entry); }
public void BloggerETagTest() { Tracing.TraceMsg("Entering BloggerETagTest"); BloggerQuery query = new BloggerQuery(); BloggerService service = new BloggerService(this.ApplicationName); service.ProtocolMajor = 2; string title = "V1" + Guid.NewGuid().ToString(); service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); // insert a new entry in version 1 AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = title; entry.IsDraft = true; BloggerEntry returnedEntry = service.Insert(new Uri(this.bloggerURI), entry) as BloggerEntry; Assert.IsTrue(returnedEntry.ProtocolMajor == service.ProtocolMajor); Assert.IsTrue(entry.IsDraft); Assert.IsTrue(returnedEntry.IsDraft); Assert.IsTrue(returnedEntry.Etag != null); string etagOld = returnedEntry.Etag; returnedEntry.Content.Content = "This is a test"; BloggerEntry newEntry = returnedEntry.Update() as BloggerEntry; Assert.IsTrue(newEntry.Etag != null); Assert.IsTrue(newEntry.Etag != etagOld); }
//============================================================ // PUBLIC METHODS //============================================================ #region Fill(AtomEntry resource) /// <summary> /// Modifies the <see cref="AtomEntry"/> to match the data source. /// </summary> /// <param name="resource">The <see cref="AtomEntry"/> to be filled.</param> /// <exception cref="ArgumentNullException">The <paramref name="resource"/> is a null reference (Nothing in Visual Basic).</exception> public void Fill(AtomEntry resource) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ Guard.ArgumentNotNull(resource, "resource"); //------------------------------------------------------------ // Create namespace resolver //------------------------------------------------------------ XmlNamespaceManager manager = AtomUtility.CreateNamespaceManager(this.Navigator.NameTable); //------------------------------------------------------------ // Attempt to fill syndication resource //------------------------------------------------------------ XPathNavigator entryNavigator = this.Navigator.SelectSingleNode("atom:entry", manager); if (entryNavigator != null) { Atom10SyndicationResourceAdapter.FillEntry(resource, entryNavigator, manager, this.Settings); } }
public static void AddEvent(CalendarService service, string id, string title, string contents, string location, DateTime startTime, DateTime endTime, string calendarName) { try { Google.GData.Calendar.EventEntry entry = new Google.GData.Calendar.EventEntry(); // Set the title and content of the entry. entry.Title.Text = id + "-" + title; entry.Content.Content = contents; // Set a location for the event. Where eventLocation = new Where(); eventLocation.ValueString = location; entry.Locations.Add(eventLocation); When eventTime = new When(startTime, endTime); entry.Times.Add(eventTime); GoogleCalendar ggadmin = new GoogleCalendar(calendarName, AdminuserName, AdminuserPwd); string CalendarId = ggadmin.GetCalendarId(); Uri postUri = new Uri("https://www.google.com/calendar/feeds/" + CalendarId + "/private/full"); GDataGAuthRequestFactory requestFactory = (GDataGAuthRequestFactory)service.RequestFactory; IWebProxy iProxy = WebRequest.GetSystemWebProxy(); WebProxy myProxy = new WebProxy(); // potentially, setup credentials on the proxy here myProxy.Credentials = CredentialCache.DefaultCredentials; myProxy.UseDefaultCredentials = false; requestFactory.CreateRequest(GDataRequestType.Insert, postUri);// = myProxy; // Send the request and receive the response: AtomEntry insertedEntry = service.Insert(postUri, entry); } catch (Exception ex) { //LogManager.Instance.WriteToFlatFile(ex.Message); } }
//============================================================ // PRIVATE METHODS //============================================================ #region LoadFrom(AtomEntry entry) /// <summary> /// Loads the generic syndication item using the supplied <see cref="AtomEntry"/>. /// </summary> /// <param name="entry">The <see cref="AtomEntry"/> to build an abstraction against.</param> /// <exception cref="ArgumentNullException">The <paramref name="entry"/> is a null reference (Nothing in Visual Basic).</exception> private void LoadFrom(AtomEntry entry) { //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(entry, "entry"); //------------------------------------------------------------ // Initialize generic item //------------------------------------------------------------ if (entry.Title != null && !String.IsNullOrEmpty(entry.Title.Content)) { itemTitle = entry.Title.Content.Trim(); } if (entry.PublishedOn != DateTime.MinValue) { itemPublishedOn = entry.PublishedOn; } else if (entry.UpdatedOn != DateTime.MinValue) { itemPublishedOn = entry.UpdatedOn; } if (entry.Summary != null && !String.IsNullOrEmpty(entry.Summary.Content)) { itemSummary = entry.Summary.Content.Trim(); } else if (entry.Content != null && !String.IsNullOrEmpty(entry.Content.Content)) { itemSummary = entry.Content.Content.Trim(); } foreach (AtomCategory category in entry.Categories) { GenericSyndicationCategory genericCategory = new GenericSyndicationCategory(category); itemCategories.Add(genericCategory); } }
/// <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> static EventEntry CreateEvent(CalendarService service, String entryTitle, String recurData) { EventEntry entry = new EventEntry(); // Set the title and content of the entry. entry.Title.Text = entryTitle; entry.Content.Content = "Meet for a quick lesson."; // Set a location for the event. Where eventLocation = new Where(); eventLocation.ValueString = "South Tennis Courts"; entry.Locations.Add(eventLocation); // If a recurrence was requested, add it. Otherwise, set the // time (the current date and time) and duration (30 minutes) // of the event. if (recurData == null) { When eventTime = new When(); eventTime.StartTime = DateTime.Now; eventTime.EndTime = eventTime.StartTime.AddMinutes(30); entry.Times.Add(eventTime); } else { Recurrence recurrence = new Recurrence(); recurrence.Value = recurData; entry.Recurrence = recurrence; } // Send the request and receive the response: Uri postUri = new Uri(feedUri); AtomEntry insertedEntry = service.Insert(postUri, entry); return((EventEntry)insertedEntry); }
private static async Task AddSyndicationItemEntry(AtomEntry <SyndicationItem <Parcel> > entry, SyndicationContext context, CancellationToken ct) { var parcelAddressMatchLatestItems = context .ParcelAddressMatchLatestItems .Where(x => x.ParcelId == entry.Content.Object.Id) .ToList() .Concat(context.ParcelAddressMatchLatestItems.Local.Where(x => x.ParcelId == entry.Content.Object.Id)) .ToList(); var itemsToRemove = new List <ParcelAddressMatchLatestItem>(); foreach (var parcelAddressMatchLatestItem in parcelAddressMatchLatestItems) { if (!entry.Content.Object.AddressIds.Contains(parcelAddressMatchLatestItem.AddressId)) { itemsToRemove.Add(parcelAddressMatchLatestItem); } } foreach (var parcelAddressMatchLatestItem in itemsToRemove) { parcelAddressMatchLatestItem.IsRemoved = true; } foreach (var addressId in entry.Content.Object.AddressIds) { if (parcelAddressMatchLatestItems.All(x => x.AddressId != addressId)) { await context.ParcelAddressMatchLatestItems.AddAsync(new ParcelAddressMatchLatestItem { ParcelId = entry.Content.Object.Id, AddressId = addressId, ParcelPersistentLocalId = entry.Content.Object.Identificator.ObjectId }, ct); } } }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the AtomPersonConstruct class. /// </summary> public static void ClassExample() { #region AtomPersonConstruct AtomFeed feed = new AtomFeed(); feed.Id = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6")); feed.Title = new AtomTextConstruct("Example Feed"); feed.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2); feed.Links.Add(new AtomLink(new Uri("http://example.org/"))); feed.Links.Add(new AtomLink(new Uri("/feed"), "self")); // Identify the author of the feed feed.Authors.Add(new AtomPersonConstruct("John Doe")); // Identify the contributors to the feed feed.Contributors.Add(new AtomPersonConstruct("Jane Doe")); AtomPersonConstruct contributor = new AtomPersonConstruct(); contributor.EmailAddress = "*****@*****.**"; contributor.Name = "Some Person"; contributor.Uri = new Uri("http://example.org/somePerson"); feed.Contributors.Add(contributor); AtomEntry entry = new AtomEntry(); entry.Id = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a")); entry.Title = new AtomTextConstruct("Atom-Powered Robots Run Amok"); entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2); entry.Summary = new AtomTextConstruct("Some text."); // Identify the author of the entry entry.Authors.Add(new AtomPersonConstruct("Jane Doe")); feed.AddEntry(entry); #endregion }
////////////////////////////////////////////////////////////////////// /// <summary>uses GData batch to batchupdate the cell feed. If the returned /// batch result set contained an error, it will throw a GDataRequestBatchException</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public override void Publish() { if (this.Batch == null) { throw new InvalidOperationException("This feed has no batch URI"); } AtomFeed batchFeed = CreateBatchFeed(GDataBatchOperationType.update); if (batchFeed != null) { AtomFeed resultFeed = this.Service.Batch(batchFeed, new Uri(this.Batch)); foreach (AtomEntry resultEntry in resultFeed.Entries) { GDataBatchEntryData data = resultEntry.BatchData; if (data.Status.Code != (int)HttpStatusCode.OK) { throw new GDataBatchRequestException(resultFeed); } } // if we get here, everything is fine. So update the edit URIs in the original feed, // because those might have changed. foreach (AtomEntry resultEntry in resultFeed.Entries) { AtomEntry originalEntry = this.Entries.FindById(resultEntry.Id); if (originalEntry == null) { throw new GDataBatchRequestException(resultFeed); } if (originalEntry != null) { originalEntry.EditUri = resultEntry.EditUri; } } } this.Dirty = false; }
public async Task Rss(string type) { Response.ContentType = "application/xml"; string host = Request.Scheme + "://" + Request.Host; using (XmlWriter xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings() { Async = true, Indent = true })) { var posts = await _blog.GetPosts(10); var writer = await GetWriter(type, xmlWriter, posts.Max(p => p.PubDate)); foreach (Models.Post post in posts) { var item = new AtomEntry { Title = post.Title, Description = post.Content, Id = host + post.GetLink(), Published = post.PubDate, LastUpdated = post.LastModified, ContentType = "html", }; foreach (string category in post.Categories) { item.AddCategory(new SyndicationCategory(category)); } item.AddContributor(new SyndicationPerson(_settings.Value.Owner, "*****@*****.**")); item.AddLink(new SyndicationLink(new Uri(item.Id))); await writer.Write(item); } } }
public async Task Rss(string type) { Response.ContentType = "application/xml"; string host = Request.Scheme + "://" + Request.Host; using (XmlWriter xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings() { Async = true, Indent = true })) { var pageViewModels = await _pageService.GetAllVisibleByRangeAsync(take : 10); var writer = await GetWriter(type, xmlWriter, pageViewModels.Max(p => p.CreatedDateTimeInDateTime)); foreach (var pageViewModel in pageViewModels) { var item = new AtomEntry { Title = pageViewModel.Title, Description = pageViewModel.BriefDescription, Id = host + $@"/page/{pageViewModel.Id}/{pageViewModel.SlugUrl}", Published = pageViewModel.CreatedDateTimeInDateTime, LastUpdated = pageViewModel.ModifiedDateTimeInDateTime ?? pageViewModel.CreatedDateTimeInDateTime, ContentType = "html", }; //foreach (string category in pageViewModel.Categories) //{ // item.AddCategory(new SyndicationCategory(category)); //} item.AddContributor(new SyndicationPerson(_settings.Value.Owner, _settings.Value.Email)); item.AddLink(new SyndicationLink(new Uri(item.Id))); await writer.Write(item); } } }
public GoogleDatabase GetDatabase(string name, ref string error) { try { Google.GData.Spreadsheets.SpreadsheetQuery query = new Google.GData.Spreadsheets.SpreadsheetQuery(); // Make a request to the API and get all spreadsheets. SpreadsheetsService service = spreadsheetService as SpreadsheetsService; SpreadsheetFeed feed = service.Query(query); if (feed.Entries.Count == 0) { error = "There are no spreadsheets found."; return(null); } AtomEntry spreadsheet = null; foreach (AtomEntry sf in feed.Entries) { if (sf.Title.Text == name) { spreadsheet = sf; } } if (spreadsheet == null) { error = string.Format("Spreadsheet: \"{0}\" is not found.", name); return(null); } return(new GoogleDatabase(spreadsheet)); } catch (Exception e) { error = e.Message; return(null); } }
/// <summary> /// Provides example code for the AtomFeed class. /// </summary> public static void ClassExample() { AtomFeed feed = new AtomFeed(); feed.Id = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6")); feed.Title = new AtomTextConstruct("Example Feed"); feed.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2); feed.Links.Add(new AtomLink(new Uri("http://example.org/"))); feed.Links.Add(new AtomLink(new Uri("/feed"), "self")); feed.Authors.Add(new AtomPersonConstruct("John Doe")); AtomEntry entry = new AtomEntry(); entry.Id = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a")); entry.Title = new AtomTextConstruct("Atom-Powered Robots Run Amok"); entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2); entry.Summary = new AtomTextConstruct("Some text."); feed.AddEntry(entry); }
/// <summary> /// Convierte las entradas RDF en entradas Atom /// </summary> private void ConvertEntries(RDFChannel rdf, AtomChannel channel) { foreach (RDFEntry rdfEntry in rdf.Entries) { AtomEntry channelEntry = new AtomEntry(); // Convierte los datos de la entrada channelEntry.ID = rdfEntry.ID; channelEntry.Title = ConvertText(rdfEntry.Title); channelEntry.Content = ConvertText(rdfEntry.Content); channelEntry.DateIssued = rdfEntry.DateCreated; channelEntry.DateCreated = rdfEntry.DateCreated; channelEntry.DateModified = rdfEntry.DateCreated; channelEntry.DateUpdated = rdfEntry.DateCreated; channelEntry.DatePublished = rdfEntry.DateCreated; // Vínculos channelEntry.Links.Add(ConvertLink(rdfEntry.Link, AtomLink.AtomLinkType.Self)); // Convierte las extensiones ConvertExtension(rdfEntry.Extensions, channelEntry.Extensions); // Añade la entrada al objeto Atom channel.Entries.Add(channelEntry); } }
public void Typical_Entry() { var xml = @"<entry xmlns=""http://www.w3.org/2005/Atom"" xmlns:sync=""http://schemas.sage.com/sdata/sync/2008/1""> <sync:syncState> <sync:endpoint>http://www.example.com/sdata/myApp1/myContract/-/accounts</sync:endpoint> <sync:tick>5</sync:tick> <sync:stamp>2008-10-30T14:55:43Z</sync:stamp> </sync:syncState> </entry>"; var entry = new AtomEntry(); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml))) { entry.Load(stream); } var syncState = entry.GetSDataSyncState(); Assert.That(syncState.EndPoint, Is.EqualTo("http://www.example.com/sdata/myApp1/myContract/-/accounts")); Assert.That(syncState.Tick, Is.EqualTo(5L)); Assert.That(syncState.Stamp, Is.EqualTo(new DateTime(2008, 10, 30, 14, 55, 43))); }
/// <summary> /// Provides example code for the Load(XmlReader) method /// </summary> public static void LoadXmlReaderExample() { #region Load(XmlReader reader) AtomEntry entry = new AtomEntry(); using (Stream stream = new FileStream("AtomEntryDocument.xml", FileMode.Open, FileAccess.Read)) { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreWhitespace = true; using (XmlReader reader = XmlReader.Create(stream, settings)) { entry.Load(reader); if (entry.UpdatedOn >= DateTime.Today) { // Perform some processing on the entry } } } #endregion }
public static async Task ParseDictionaryAsyncAtomFeed() { // Test to verify GitHub PR #57 - handling empty key name to "Empty" for <s:key name=""> var path = Path.Combine(Directory, "AtomFeed.EmptyDictionaryKeyNameAtomFeed.xml"); using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { var reader = XmlReader.Create(stream, TestAtomFeed.XmlReaderSettings); var feed = new AtomFeed(); await feed.ReadXmlAsync(reader); Assert.Equal(1, feed.Entries.Count); AtomEntry entry = feed.Entries[0]; dynamic content = entry.Content; Assert.NotNull(content); Assert.NotNull(content["Key"]); Assert.NotNull(content["Key"]["Empty"]); Assert.Equal(1, ((IDictionary <string, object>)content["Key"]["Empty"]).Count); Assert.Equal("num", content["Key"]["Empty"]["Type"]); Assert.Equal(new ReadOnlyDictionary <string, Uri>(new Dictionary <string, Uri>()), feed.Links); Assert.Equal(new ReadOnlyCollection <Message>(new List <Message>()), feed.Messages); } }
/// <summary> /// Updates information about a syndication resource in the data source. /// </summary> /// <param name="request">The url from the syndication data source for the resource to be updated.</param> /// <param name="entry"> /// An object that implements the <see cref="ISyndicationResource"/> interface that represents the updated information for the resource. /// </param> public virtual AtomEntry UpdateEntry(SDataBaseRequest request, AtomEntry entry) { Guard.ArgumentNotNull(request, "request"); Guard.ArgumentNotNull(entry, "entry"); try { var url = request.ToString(); var eTag = entry.GetSDataHttpETag(); var batchItem = new SDataBatchRequestItem { Url = url, Method = HttpMethod.Put, Entry = entry, ETag = eTag }; if (BatchProcess.Instance.AddToBatch(batchItem)) { return(null); } var operation = new RequestOperation(HttpMethod.Put, entry) { ETag = eTag }; return(ExecuteEntryRequest(url, operation)); } catch (SDataClientException) { throw; } catch (Exception ex) { throw new SDataClientException(ex.Message, ex); } }
public AtomEntry createWebPage(String originalUrl, String path, String title, String html, String pageName, DateTime lastModified) { String parentUrl = "https://sites.google.com/feeds/content/site/" + sitename + "?path=" + path; if (this.debugFlag) { printDebugMessage("Creating page " + parentUrl + "/" + pageName); } AtomEntry parent = service.Get(parentUrl); SiteEntry entry = new SiteEntry(); AtomCategory category = new AtomCategory(SitesService.WEBPAGE_TERM, SitesService.KIND_SCHEME); category.Label = "webpage"; entry.Categories.Add(category); AtomLink link = new AtomLink("application/atom+xml", "http://schemas.google.com/sites/2008#parent"); link.HRef = parent.EditUri; entry.Links.Add(link); entry.Title.Text = IndianBridge.Common.Utility.ConvertCaseString(title); entry.Content.Type = "html"; entry.Content.Content = html; entry.ExtensionElements.Add(makePageNameExtension(pageName)); AtomEntry newEntry = null; String url = "https://sites.google.com/feeds/content/site/" + sitename; newEntry = service.Insert(new Uri(url), entry); lastRunTimes[originalUrl] = lastModified; /*TextWriter tw = new StreamWriter(m_hashTableFileName, true); * tw.WriteLine(originalUrl + "," + lastModified); * tw.Close();*/ if (this.debugFlag) { printDebugMessage(parentUrl + "/" + pageName + " - Created."); } return(newEntry); }
private async Task AddSyndicationItemEntry(AtomEntry <SyndicationItem <Parcel> > entry, SyndicationContext context, CancellationToken ct) { var addressParcelLinkExtractItems = context .AddressParcelLinkExtract .Where(x => x.ParcelId == entry.Content.Object.Id) .AsEnumerable() .Concat(context.AddressParcelLinkExtract.Local.Where(x => x.ParcelId == entry.Content.Object.Id)) .ToList(); var itemsToRemove = new List <AddressParcelLinkExtractItem>(); foreach (var addressParcelLinkExtractItem in addressParcelLinkExtractItems) { if (!entry.Content.Object.AddressIds.Contains(addressParcelLinkExtractItem.AddressId)) { itemsToRemove.Add(addressParcelLinkExtractItem); } } context.AddressParcelLinkExtract.RemoveRange(itemsToRemove); foreach (var addressId in entry.Content.Object.AddressIds) { var addressItem = addressParcelLinkExtractItems.FirstOrDefault(x => x.AddressId == addressId); if (addressItem == null) { await context.AddressParcelLinkExtract.AddAsync( await CreateAddressParcelLinkExtractItem(entry, addressId, context), ct); } else { addressItem.ParcelPersistentLocalId = entry.Content.Object.Identificator.ObjectId; UpdateDbaseRecordField(addressItem, record => record.adresobjid.Value = entry.Content.Object.Identificator.ObjectId); } } }
public FeedItem(ISyndicationItem item, DateTimeOffset recent, Uri website) { Title = item.Title; ISyndicationLink firstLink = item.Links.FirstOrDefault(x => x.RelationshipType == RssLinkTypes.Alternate); if (firstLink != null) { Link = firstLink.Uri.IsAbsoluteUri ? firstLink.Uri.AbsoluteUri : new Uri(website, firstLink.Uri).AbsoluteUri; } else { Link = item.Id; } Published = item.Published != default ? item.Published : item.LastUpdated; Recent = Published > recent; Description = item.Description; Links = item.Links .Where(x => !string.IsNullOrEmpty(x.MediaType)) .GroupBy(x => x.MediaType) .Select(x => x.First()) .ToDictionary(x => x.MediaType, x => x.Uri.ToString()); ISyndicationPerson person = item.Contributors.FirstOrDefault(x => x.RelationshipType == "author"); if (person != null) { Author = person.Name ?? person.Email; } AtomEntry atom = item as AtomEntry; if (atom != null && !string.IsNullOrEmpty(atom.Summary)) { Description = atom.Summary; } }
private static async Task AddSyndicationItemEntry(AtomEntry <SyndicationItem <StreetName> > entry, SyndicationContext context, CancellationToken ct) { var latestItem = await context .StreetNameLatestItems .FindAsync(entry.Content.Object.StreetNameId); if (latestItem == null) { latestItem = new StreetNameLatestItem { StreetNameId = entry.Content.Object.StreetNameId, NisCode = entry.Content.Object.NisCode, Version = entry.Content.Object.Identificator?.Versie, Position = long.Parse(entry.FeedEntry.Id), PersistentLocalId = entry.Content.Object.Identificator?.ObjectId, IsComplete = entry.Content.Object.IsComplete }; UpdateNames(latestItem, entry.Content.Object.StreetNames); UpdateHomonymAdditions(latestItem, entry.Content.Object.HomonymAdditions); await context .StreetNameLatestItems .AddAsync(latestItem, ct); } else { latestItem.NisCode = entry.Content.Object.NisCode; latestItem.Version = entry.Content.Object.Identificator?.Versie; latestItem.Position = long.Parse(entry.FeedEntry.Id); latestItem.PersistentLocalId = entry.Content.Object.Identificator?.ObjectId; latestItem.IsComplete = entry.Content.Object.IsComplete; UpdateNames(latestItem, entry.Content.Object.StreetNames); UpdateHomonymAdditions(latestItem, entry.Content.Object.HomonymAdditions); } }
/// <summary> /// Convierte las entradas RSS en entradas Atom /// </summary> private void ConvertEntries(RSSChannel rss, AtomChannel channel) { foreach (RSSEntry rssEntry in rss.Entries) { AtomEntry channelEntry = new AtomEntry(); // Convierte los datos de la entrada channelEntry.ID = rssEntry.ID; channelEntry.Title = ConvertText(rssEntry.Title); channelEntry.Content = ConvertText(rssEntry.Content); channelEntry.DateIssued = rssEntry.DateCreated; channelEntry.DateCreated = rssEntry.DateCreated; channelEntry.DateModified = rssEntry.DateCreated; channelEntry.DateUpdated = rssEntry.DateCreated; channelEntry.DatePublished = rssEntry.DateCreated; // Vínculos channelEntry.Links.Add(ConvertLink(rssEntry.Link, AtomLink.AtomLinkType.Self)); foreach (RSSEnclosure rssEnclosure in rssEntry.Enclosures) { channelEntry.Links.Add(ConvertLink(rssEnclosure)); } // Autores foreach (RSSAuthor rssAuthor in rssEntry.Authors) { channelEntry.Authors.Add(ConvertAuthor(rssAuthor)); } // Categorías foreach (RSSCategory rssCategory in rssEntry.Categories) { channelEntry.Categories.Add(ConvertCategory(rssCategory)); } // Convierte las extensiones ConvertExtension(rssEntry.Extensions, channelEntry.Extensions); // Añade la entrada al objeto Atom channel.Entries.Add(channelEntry); } }
private void PostNoticeUrl(Notice notice, string url) { AtomEntry entry = new AtomEntry(); entry.Title.Text = notice.Subject; entry.Content.Content = notice.Subject; entry.Content.Type = notice.ContentType; if (notice.CareRecord != null) { XmlSerializer serializer = new XmlSerializer(typeof(ContinuityOfCareRecord)); using (StringWriter strWriter = new StringWriter()) { XmlTextWriter writer = new XmlTextWriter(new StringWriter()); serializer.Serialize(writer, notice.CareRecord); XmlDocument doc = new XmlDocument(); doc.LoadXml(strWriter.ToString()); entry.ExtensionElements.Add(new XmlExtension(doc.DocumentElement)); } } notice = Notice.FromAtomEntry(this.Insert(new Uri(url), entry)); }
public AtomEntry GetEntry(Id entryId) { ItemDataContext dc = new ItemDataContext(); Item item = dc.Items.Where(i => i.Id == entryId.ToString()).SingleOrDefault(); SyndicationItem si = new SyndicationItem() { Id = item.Id, LastUpdatedTime = item.LastUpdatedTime, PublishDate = item.PublishDate.Value }; if (!string.IsNullOrEmpty(item.BaseUri)) si.BaseUri = new Uri(item.BaseUri); LoadAttributes(si.AttributeExtensions, item.Attributes); LoadElements(si.ElementExtensions, item.Elements); LoadPersons(si.Authors, item.Persons, PersonTypeAuthor); LoadPersons(si.Contributors, item.Persons, PersonTypeContributor); si.Content = GetContent(item.Content); si.Title = GetTextContent(item.Title); si.Summary = GetTextContent(item.Summary); si.Copyright = GetTextContent(item.Copyright); LoadLinks(si.Links, item.Links); LoadCategories(si.Categories, item.Categories); using (Stream s = new MemoryStream()) { XmlWriter w = new XmlTextWriter(s, Encoding.UTF8); si.GetAtom10Formatter().WriteTo(w); w.Flush(); AtomEntry entry = new AtomEntry(); s.Position = 0; XmlReader r = new XmlTextReader(s); entry.Xml = XElement.Load(r); //entry.ReadXml(r); return entry; } }
/// <summary> /// Modifies the <see cref="AtomEntry"/> optional entities to match the supplied <see cref="XPathNavigator"/> data source. /// </summary> /// <param name="entry">The <see cref="AtomEntry"/> to be filled.</param> /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param> /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param> /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the fill operation.</param> /// <remarks> /// This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents an Atom 0.3 element. /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="entry"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="manager"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="settings"/> is a null reference (Nothing in Visual Basic).</exception> private static void FillEntryOptionals(AtomEntry entry, XPathNavigator source, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ Guard.ArgumentNotNull(entry, "entry"); Guard.ArgumentNotNull(source, "source"); Guard.ArgumentNotNull(manager, "manager"); Guard.ArgumentNotNull(settings, "settings"); //------------------------------------------------------------ // Attempt to extract syndication information //------------------------------------------------------------ XPathNavigator contentNavigator = source.SelectSingleNode("atom:content", manager); XPathNavigator createdNavigator = source.SelectSingleNode("atom:created", manager); XPathNavigator summaryNavigator = source.SelectSingleNode("atom:summary", manager); if (contentNavigator != null) { entry.Content = Atom03SyndicationResourceAdapter.CreateContent(contentNavigator, manager, settings); } if (createdNavigator != null) { DateTime publishedOn; if (SyndicationDateTimeUtility.TryParseRfc3339DateTime(createdNavigator.Value, out publishedOn)) { entry.PublishedOn = publishedOn; } } if (summaryNavigator != null) { entry.Summary = Atom03SyndicationResourceAdapter.CreateTextContent(summaryNavigator, manager, settings); } }
public void addEvent(string lugar, DateTime inicio, double duracion, string asunto, string contenido, IList <Participantes> participantes) { Where location = new Where() { ValueString = lugar }; Reminder reminder = new Reminder() { Hours = 1, Method = Reminder.ReminderMethod.email }; When time = new When(inicio, inicio.AddHours(duracion)); time.Reminders.Add(reminder); CalendarService service = new CalendarService("GESAC"); service.setUserCredentials(Correo, Contraseña); EventEntry entry = new EventEntry(); entry.Title.Text = asunto; entry.Content.Content = contenido; entry.Notifications = true; entry.Locations.Add(location); entry.Times.Add(time); foreach (Participantes p in participantes) { entry.Participants.Add(new Who() { ValueString = p.Nombre, Email = p.Correo, Rel = "nofollow" }); } AtomEntry insert = service.Insert(CalendarURI, entry); }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the AtomCategory class. /// </summary> public static void ClassExample() { #region AtomCategory AtomFeed feed = new AtomFeed(); feed.Id = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6")); feed.Title = new AtomTextConstruct("Example Feed"); feed.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2); feed.Links.Add(new AtomLink(new Uri("http://example.org/"))); feed.Links.Add(new AtomLink(new Uri("/feed"), "self")); feed.Authors.Add(new AtomPersonConstruct("John Doe")); // Categorize the feed feed.Categories.Add(new AtomCategory("sports")); AtomEntry entry = new AtomEntry(); entry.Id = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a")); entry.Title = new AtomTextConstruct("Atom-Powered Robots Run Amok"); entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2); entry.Summary = new AtomTextConstruct("Some text."); // Categorize the feed entry AtomCategory entryCategory = new AtomCategory(); entryCategory.Label = "Baseball"; entryCategory.Scheme = new Uri("http://example.org/scheme/category"); entryCategory.Term = "baseball"; entry.Categories.Add(entryCategory); feed.AddEntry(entry); #endregion }
///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerStressTest() { Tracing.TraceMsg("Entering Blogger GoogleStressTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); AtomFeed blogFeed = service.Query(query); ObjectModelHelper.DumpAtomObject(blogFeed, CreateDumpFileName("AuthenticationTest")); if (blogFeed != null) { for (int i = 0; i < 30; i++) { AtomEntry entry = ObjectModelHelper.CreateAtomEntry(i); entry.Categories.Clear(); entry.Title.Text = "Title " + i; entry.Content.Content = "Some text..."; entry.Content.Type = "html"; blogFeed.Insert(entry); } } } }
private static Task DoNothing(AtomEntry <SyndicationItem <Municipality> > entry, SyndicationContext context, CancellationToken ct) => Task.CompletedTask;
protected void SetPerson(AtomEntry entry) { entry.SetPerson(AuthorizeService); }
public virtual AtomEntry UpdateEntry(Id entryId, AtomEntry entry, string slug) { LogService.Info("AtomPubService.UpdateEntry entryId={0}", entryId); Auth(entryId, AuthAction.UpdateEntryOrMedia); //ensure existing entry exists AtomEntry old = AtomEntryRepository.GetEntry(entryId); //copy old approval setting when not authorized to approve if (!AuthorizeService.IsAuthorized(GetUser(), entryId.ToScope(), AuthAction.ApproveEntryOrMedia)) { if (entry.Control != null && entry.Control.Approved.HasValue) entry.Control.Approved = old.Control.Approved; else entry.Control.Approved = false; } if (!entry.Draft && !entry.Published.HasValue) entry.Published = DateTimeOffset.UtcNow; entry.Updated = DateTimeOffset.UtcNow; entry.Edited = DateTimeOffset.UtcNow; //if (old.Draft) //allow Id to change when old was draft mode, is this safe? //{ // AppCollection coll = AppServiceRepository.GetService().GetCollection(entryId); // if (coll.Dated) // entry.Id = new Id(coll.Id.Owner, entry.Date.UtcDateTime, coll.Id.Collection, entry.BuildPath(null, slug)); // else // entry.Id = new Id(coll.Id.Owner, coll.Id.Date, coll.Id.Collection, entry.BuildPath(null, slug)); //} //else entry.Id = entryId; //reset Id (it shouldn't change) if (old.Media) entry.Content = old.Content; //reset Content (it shouldn't change for media link entries) //entry.UpdateLinks(RouteFunc); SetPerson(entry); SetCategories(entry); SetLinks(entry); entry.IdChanged += (e) => SetLinks(e);// e.UpdateLinks(RouteFunc); //in case of changes during draft if (UpdatingEntry != null) UpdatingEntry(entryId, entry, slug); entry = AtomEntryRepository.UpdateEntry(entry); if (EntryUpdated != null) EntryUpdated(entry); return entry; }
/// <summary> /// constructor. takes the async data blob /// </summary> /// <param name="data">async data to constructor</param> internal AsyncOperationCompletedEventArgs(AsyncData data) : base(data.Exception, false, data.UserData) { feedObject = data.Feed; stream = data.DataStream; AsyncSendData sData = data as AsyncSendData; if (sData != null) { entryObject = sData.Entry; } }
public JsonResult QuickPub(string id, string title, string content, string submit) { try { if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(content)) throw new Exception("Both the title and content are required."); AtomEntry entry = new AtomEntry(); entry.Title = new AtomTitle() { Text = title }; entry.Content = new AtomContent() { Text = content, Type = "html" }; if (submit != "Publish") entry.Control = new AppControl() { Draft = true }; entry = AtomPubService.CreateEntry(id, entry, null); string message = (entry.Published.HasValue) ? "<strong>Entry Published</strong>" : "<strong>Draft Saved</strong>"; message += string.Format(" <a href='{0}'>View entry</a> | <a href='{1}'>Edit entry</a>", entry.LocationWeb, Url.Action("EditEntry", "Admin", new { id = entry.Id })); return Json(new { message = message }); } catch (Exception ex) { LogService.Error(ex); return Json(new { error = ex.Message }); } }
//TODO: this is complex, is there a better design? protected void SetCategories(AtomEntry entry) { LogService.Info("AtomPubService.SetCategories entryId={0}", entry.Id); AppService service = AppServiceRepository.GetService(); bool changed = false; AppCollection coll = service.GetCollection(entry.Id); //get all external categories Dictionary<AppCategories, KeyValuePair<AppCategories, bool>> external = new Dictionary<AppCategories, KeyValuePair<AppCategories, bool>>(); foreach (AppCategories cats in coll.Categories) { if (cats.IsExternal) external.Add(AppCategoriesRepository.GetCategories(coll.Id, cats), new KeyValuePair<AppCategories, bool>(cats, false)); } //add to either internal or external foreach (AtomCategory cat in entry.Categories) { AppCategories cats = coll.Categories.Where(c => !c.IsExternal && c.Scheme == cat.Scheme).SingleOrDefault(); if (cats != null && cats.AddCategory(cat)) { LogService.Info("Added internal category {0}", cat.Term); changed = true; } else { //look in external if (external.Keys.Where(e => e.Scheme == cat.Scheme).SingleOrDefault() != null) { KeyValuePair<AppCategories, KeyValuePair<AppCategories, bool>> ex = external.Where(e => e.Key.Scheme == cat.Scheme).Single(); if (ex.Key.AddCategory(cat)) { external.Remove(ex.Key); external.Add(ex.Key, new KeyValuePair<AppCategories, bool>(ex.Value.Key, true)); LogService.Info("Added external category {0}", cat.Term); } } } } //save when changed if (changed) { LogService.Info("Saving service doc for internal category changes."); AppServiceRepository.UpdateService(service); } //save external when changed foreach (KeyValuePair<AppCategories, KeyValuePair<AppCategories, bool>> ex in external) { if (ex.Value.Value) { LogService.Info("Saving external category changes for {0}", ex.Value.Key.Href); AppCategoriesRepository.UpdateCategories(coll.Id, ex.Value.Key, ex.Key); } } }
public GoogleDatabase(AtomEntry entry) { this.entry = entry; RefreshWorksheets(); }
public virtual AtomEntry Annotate(Id entryId, AtomEntry entry, string slug) { LogService.Info("AnnotateService.Annotate entryId={0} slug={1}", entryId, slug); //authorization if (!AuthorizeService.IsAuthorized(GetUser(), entryId.ToScope(), AuthAction.Annotate)) throw new UserNotAuthorizedException(GetUser().Name, AuthAction.Annotate.ToString()); AppCollection coll = AppService.GetCollection(entryId); //make sure type is accepted if (!coll.CanAccept(Atom.ContentTypeEntry)) throw new InvalidContentTypeException(Atom.ContentTypeEntry); entry.SetNamespaces(); //TODO: is there a better place for this? //build id onto parent's id AtomEntry parent = AtomPubService.GetEntry(entryId); entry.Id = new Id(parent.Id.Owner, parent.Id.Date, parent.Id.Collection, entry.BuildPath(parent.Id.EntryPath, slug)); var url = new UrlHelper(Container.GetInstance<RequestContext>()); //this annotation is a reply to the parent entry, TODO: leave off href for later calc based on id? entry.InReplyTo = new ThreadInReplyTo() { Ref = parent.Id, Href = parent.IsExternal ? parent.Content.Src : url.RouteIdUri("AtomPubEntry", entry.Id, AbsoluteMode.Force), Type = parent.IsExternal ? parent.Content.Type : Atom.ContentTypeEntry }; if (!entry.Published.HasValue) entry.Published = DateTimeOffset.UtcNow; entry.Updated = DateTimeOffset.UtcNow; entry.Edited = DateTimeOffset.UtcNow; if (entry.Authors.Count() == 0) entry.SetPerson(AuthorizeService, true); //entry.IdChanged += (e) => e.UpdateLinks(UrlHelper.RouteIdUri); //OnAnnotate(parent, entryId, entry, slug); if (AnnotatingEntry != null) AnnotatingEntry(entryId, entry, slug); if (entry.Authors.Count() == 0 || entry.Authors.First().Name == null) throw new AnnotationNotAllowedException(entry.Id, entry.AnnotationType, "the author cannot be determined"); entry = AtomEntryRepository.CreateEntry(entry); if (EntryAnnotated != null) EntryAnnotated(entry); return entry; }
protected void SetLinks(AtomEntry entry) { LogService.Debug("AtomPubService.SetLinks entryId={0}", entry.Id); if (entry.Links == null) entry.Links = new List<AtomLink>(); var links = entry.Links.ToList(); var url = new UrlHelper(Container.GetInstance<RequestContext>()); if (AuthorizeService.IsAuthorized(GetUser(), entry.Id.ToScope(), AuthAction.UpdateEntryOrMedia)) { links.Merge(new AtomLink { Rel = "edit", Href = url.RouteIdUri("AtomPubEntryEdit", entry.Id, AbsoluteMode.Force ), }); } links.Merge(new AtomLink { Rel = "self", Href = url.RouteIdUri("AtomPubEntry", entry.Id, AbsoluteMode.Force) }); if (entry.Media) { if (entry.Content == null) entry.Content = new AtomContent(); entry.Content.Src = url.RouteIdUri("AtomPubMedia", entry.Id, AbsoluteMode.Force); if (AuthorizeService.IsAuthorized(GetUser(), entry.Id.ToScope(), AuthAction.UpdateEntryOrMedia)) { links.Merge(new AtomLink { Rel = "edit-media", Href = url.RouteIdUri("AtomPubMediaEdit", entry.Id, AbsoluteMode.Force) }); } } else { links.Merge(new AtomLink { Rel = "alternate", Type="text/html", Href = url.RouteIdUri("AtomPubResource", entry.Id, AbsoluteMode.Force) }); } if (AuthorizeService.IsAuthorized(GetUser(), entry.Id.ToScope(), AuthAction.ApproveEntryOrMedia)) { links.RemoveAll(l => l.Rel == "unapprove" || l.Rel == "approve"); links.Add(new AtomLink { Rel = entry.Approved ? "unapprove" : "approve", Href = url.RouteIdUri("AtomPubApproveEntry", entry.Id, AbsoluteMode.Force) }); } entry.Links = links; if (SettingEntryLinks != null) SettingEntryLinks(entry); }
public virtual AtomEntry CreateMedia(Id collectionId, Stream stream, string slug, string contentType) { LogService.Info("AtomPubService.CreateMedia collectionId={0} slug={1} contentType={2}", collectionId, slug, contentType); Auth(collectionId, AuthAction.CreateEntryOrMedia); AppCollection coll = AppServiceRepository.GetService().GetCollection(collectionId); if (!coll.CanAccept(contentType)) throw new InvalidContentTypeException(contentType); AtomEntry entry = new AtomEntry(); entry.Media = true; entry.Title = new AtomText(Atom.AtomNs + "title") { Text = slug != null ? slug : collectionId.Collection }; entry.Updated = DateTimeOffset.UtcNow; entry.Edited = DateTimeOffset.UtcNow; if (!entry.Published.HasValue) entry.Published = DateTimeOffset.UtcNow; if (coll.Dated) entry.Id = new Id(collectionId.Owner, entry.Date.UtcDateTime, collectionId.Collection, entry.BuildPath(null, slug)); else entry.Id = new Id(collectionId.Owner, collectionId.Date, collectionId.Collection, entry.BuildPath(null, slug)); entry.Content = new AtomContent { Type = contentType };//, Src = UrlHelper.RouteIdUri("AtomPubMedia", entry.Id, AbsoluteMode.Force) }; SetPerson(entry); SetLinks(entry); entry.Summary = new AtomText(Atom.AtomNs + "summary") { Text = "" }; entry.IdChanged += (e) => SetLinks(e);// e.UpdateLinks(RouteFunc); if (CreatingEntry != null) CreatingEntry(collectionId, entry, slug); //OnCreateMedia(entry, collectionId, stream, slug, contentType); entry = MediaRepository.CreateMedia(entry, stream); if (EntryCreated != null) EntryCreated(entry); return entry; }
/// <summary> /// Instantiates a <see cref="ISyndicationResource"/> that conforms to the specified <see cref="SyndicationContentFormat"/> using the supplied <see cref="Stream"/>. /// </summary> /// <param name="stream">The <see cref="Stream"/> used to load the syndication resource.</param> /// <param name="format">A <see cref="SyndicationContentFormat"/> enumeration value that indicates the type syndication resource the <paramref name="stream"/> represents.</param> /// <returns> /// An <see cref="ISyndicationResource"/> object that conforms to the specified <paramref name="format"/>, initialized using the supplied <paramref name="stream"/>. /// If the <paramref name="format"/> is not supported by the provider, returns a <b>null</b> reference. /// </returns> /// <exception cref="ArgumentNullException">The <paramref name="stream"/> is a null reference (Nothing in Visual Basic).</exception> private static ISyndicationResource BuildResource(SyndicationContentFormat format, Stream stream) { Guard.ArgumentNotNull(stream, "stream"); if (format == SyndicationContentFormat.Apml) { ApmlDocument document = new ApmlDocument(); document.Load(stream); return(document); } else if (format == SyndicationContentFormat.Atom) { XPathDocument document = new XPathDocument(stream); XPathNavigator navigator = document.CreateNavigator(); navigator.MoveToRoot(); navigator.MoveToChild(XPathNodeType.Element); if (String.Compare(navigator.LocalName, "entry", StringComparison.OrdinalIgnoreCase) == 0) { AtomEntry entry = new AtomEntry(); entry.Load(navigator); return(entry); } else if (String.Compare(navigator.LocalName, "feed", StringComparison.OrdinalIgnoreCase) == 0) { AtomFeed feed = new AtomFeed(); feed.Load(navigator); return(feed); } else { return(null); } } else if (format == SyndicationContentFormat.BlogML) { BlogMLDocument document = new BlogMLDocument(); document.Load(stream); return(document); } else if (format == SyndicationContentFormat.Opml) { OpmlDocument document = new OpmlDocument(); document.Load(stream); return(document); } else if (format == SyndicationContentFormat.Rsd) { RsdDocument document = new RsdDocument(); document.Load(stream); return(document); } else if (format == SyndicationContentFormat.Rss) { RssFeed feed = new RssFeed(); feed.Load(stream); return(feed); } else { return(null); } }
protected void SetPerson(AtomEntry entry) { if (entry.Authors.Count() == 0) entry.SetPerson(AuthorizeService); }