This RSSContentProvider derive from an old CMS 6 example of the XMLPageProvider documented here http://world.episerver.com/documentation/Items/Tech-Notes/EPiServer-CMS-6/EPiServer-CMS-60/XmlPageProvider/

Firstly LoadChildrenReferencesAndTypes is called if not cached, mapping up all the providers ContentReference in EPiServer with MappedIdentity.ConstructExternalIdentifier and IdentityMappingService.
Secondly all ContentReference are call thru LoadContent, where the content is created.
ListMatchingSegments is used by the routing system to match the url segment with the ContentReference.
You’ll need an EPiServer page with equivalent properties “IntroText”, “MainBody” and “DocumentUrl”.
Register the provider in web.config:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <episerver> <contentProvider> <providers> <add entryPoint="100" filePath="http://devblog.gosso.se/feed/" name="RSSDevBlog" contentType="Your.EpiPageType.ToUse" type="Gosso.EPiStuff.ContentProviders.RSSContentProvider, Gosso.EPiStuff" /> </providers> </contentProvider> </episerver> </configuration> |
RSS Content Provider C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
using EPiServer; using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.Security; using EPiServer.Web; using EPiServer.Web.Routing; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Globalization; using System.Linq; using System.Web; using System.Xml.Linq; namespace Gosso.EPiStuff.ContentProviders { public class RSSContentProvider : EPiServer.Core.ContentProvider { private string _filePath; private string _contentType; private readonly IdentityMappingService _identityMappingService; private readonly IContentTypeRepository _contentTypeRepository; private readonly IContentFactory _contentFactory; private readonly ServiceLocationHelper locator; private readonly IUrlSegmentGenerator _urlSegment; private readonly CategoryRepository categoryRepository; private readonly IContentCacheKeyCreator _cacheCreator; public RSSContentProvider(IdentityMappingService identityMappingService, IContentTypeRepository _ContentTypeRepository, IContentFactory _ContentFactory, ServiceLocationHelper _Locator, IUrlSegmentGenerator _UrlSegment, IContentCacheKeyCreator _CacheCreator) { _identityMappingService = identityMappingService; _contentTypeRepository = _ContentTypeRepository; _contentFactory = _ContentFactory; locator = _Locator; _urlSegment = _UrlSegment; _cacheCreator = _CacheCreator; } #region overrides from base class /// <summary> /// Initializes the provider from configuration settings. /// </summary> /// <param name="key">The key.</param> /// <param name="configParams">The config params.</param> public override void Initialize(string key, NameValueCollection configParams) { //Let base classes do their initialization base.Initialize(key, configParams); //Make sure a path to the backing xml file is given in configuration of page provider if (configParams["filePath"] == null) { throw new ConfigurationErrorsException("RSSContentProvider requires configuration attribute filePath that should be a application relative path"); } if (configParams["contentType"] == null) { throw new ConfigurationErrorsException("RSSContentProvider requires configuration attribute contentType that should be ContentType"); } _filePath = HttpUtility.UrlEncode(configParams["filePath"]); _contentType = HttpUtility.UrlEncode(configParams["contentType"]); } protected override IContent LoadContent(ContentReference contentLink, ILanguageSelector languageSelector) { try { MappedIdentity mappedIdentity = _identityMappingService.Get(contentLink); if (mappedIdentity != null && mappedIdentity.ExternalIdentifier != null) { // SOMETIME PARENT IS CALLED FIRST!! breaking change CMS 8 : Possible to set EntryPoint for content provider that have exactly 1 child string rssGuid = mappedIdentity.ExternalIdentifier.PathAndQuery.TrimStart('/'); RSSPage rsspage = (from page in XmlPages.Descendants("item") where string.Equals(page.GetValue<string>("guid"), rssGuid) select new RSSPage { Guid = page.GetValue<string>("guid"), Title = page.GetValue<string>("title"), Description = page.GetValue<string>("description"), Content = page.GetValue<string>("{http://purl.org/rss/1.0/modules/content/}encoded"), PubDate = page.GetValue<DateTime>("pubDate"), Language = page.Parent.Element("language").Value, DocumentUrl = page.GetAttributeFromElement<string>("enclosure", "url") }).FirstOrDefault<RSSPage>(); if (rsspage != null) { return CreateContent(mappedIdentity, rsspage); } else { //handle return null; } } } catch (Exception) { //handle exception } return null; } public IContent CreateContent(MappedIdentity mappedIdentity, RSSPage rsspage) { ContentType type = _contentTypeRepository.Load(Type.GetType(_contentType)); var mirrored = _contentFactory.CreateContent(type); mirrored.ContentTypeID = type.ID; mirrored.ParentLink = new PageReference(EntryPoint.ID); mirrored.ContentLink = mappedIdentity.ContentLink; mirrored.ContentGuid = mappedIdentity.ContentGuid; // not this one! May cause loop //mirrored.Property["PageLinkURL"].Value = this.ConstructContentUri(contentTypeId, content.ContentLink, content.ContentGuid); ILocalizable localizable = mirrored as ILocalizable; var langs = new List<CultureInfo>(); langs.Add(new CultureInfo(rsspage.Language)); localizable.ExistingLanguages = langs; localizable.Language = new CultureInfo(rsspage.Language); //add date to url segment (mirrored as IRoutable).RouteSegment = _urlSegment.GetUrlFriendlySegment(mirrored.Name + "-" + rsspage.PubDate.ToString("yyyy-MM-dd")); //add role everyone (mirrored as IContentSecurable).GetContentSecurityDescriptor().AddEntry(new AccessControlEntry(EveryoneRole.RoleName, AccessLevel.Read)); var versionable = mirrored as IVersionable; if (versionable != null) { versionable.Status = VersionStatus.Published; } PageData pd = new PageData(); pd = (mirrored as PageData); pd.Name = rsspage.Title; pd.LinkType = PageShortcutType.Normal; string description = HttpUtility.HtmlDecode(rsspage.Description); if (!string.IsNullOrWhiteSpace(description)) { pd["IntroText"] = description; } string content = HttpUtility.HtmlDecode(rsspage.Content); if (!string.IsNullOrWhiteSpace(content)) { pd["MainBody"] = content; } pd.StartPublish = rsspage.PubDate; pd["PageChanged"] = rsspage.PubDate; pd["PageCreated"] = rsspage.PubDate; pd["DocumentUrl"] = rsspage.DocumentUrl; //pd["Categories"] = "23,34,233"; //list of categories if you want pd.LanguageID = rsspage.Language; pd.MakeReadOnly(); AddContentToCache(mirrored); return mirrored; } protected override IList<GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageID, out bool languageSpecific) { languageSpecific = false; if (contentLink == this.EntryPoint) { IList<GetChildrenReferenceResult> list = new List<GetChildrenReferenceResult>(); try { List<string> pageLanguages = new List<string>(); foreach (var page in XmlPages.Descendants("item")) { var rsspage = new RSSPage { Guid = page.GetValue<string>("guid"), Title = page.GetValue<string>("title"), Description = page.GetValue<string>("description"), Content = page.GetValue<string>("{http://purl.org/rss/1.0/modules/content/}encoded"), PubDate = page.GetValue<DateTime>("pubDate"), Language = page.Parent.Element("language").Value, DocumentUrl = page.GetAttributeFromElement<string>("enclosure", "url") }; try { Uri externalID = MappedIdentity.ConstructExternalIdentifier(ProviderKey, rsspage.Guid); var mappedIdentity = _identityMappingService.Get(externalID, true); if (rsspage != null) { Type modelType = Type.GetType(_contentType); GetChildrenReferenceResult result = new GetChildrenReferenceResult { ContentLink = mappedIdentity.ContentLink, ModelType = modelType, IsLeafNode = true }; list.Add(result); } } catch (Exception) { //todo: Logging } } return list; } catch (Exception) { //todo: Logging } return null; } return null; } protected override IList<MatchingSegmentResult> ListMatchingSegments(ContentReference parentLink, string urlSegment) { var list = new List<MatchingSegmentResult>(); foreach (var child in LoadChildren<IContent>(parentLink, LanguageSelector.Fallback("en", true), -1, -1)) { var routable = child as Holmen.Externweb.Web.EpiPageTypes.HolmenGroup.Press.NewsPressReleaseReportsBase; var isMatch = routable != null && urlSegment.Equals(routable.URLSegment, StringComparison.OrdinalIgnoreCase); if (isMatch) { list.Add(new MatchingSegmentResult { ContentLink = child.ContentLink }); } } return list; } #endregion #region Private methods private string CacheKey { get { return this.Name; } } #endregion #region properties public XDocument XmlPages { get { var pages = CacheManager.Get(CacheKey) as XDocument; if (pages == null) { try { pages = XDocument.Load(HttpUtility.UrlDecode(_filePath), LoadOptions.PreserveWhitespace); } catch (Exception) { //todo handle } CacheManager.Insert( CacheKey, pages); } return pages; } } #endregion #region cache /// <summary> /// The set cache settings. /// </summary> /// <param name="content"> /// The content. /// </param> /// <param name="cacheSettings"> /// The cache settings. /// </param> protected override void SetCacheSettings(IContent content, CacheSettings cacheSettings) { if (content == null || cacheSettings == null) { return; } // Make the cache of this content provider depend on the original content cacheSettings.CacheKeys.Add(_cacheCreator.CreateCommonCacheKey(new ContentReference(content.ContentLink.ID))); } protected override void SetCacheSettings(ContentReference contentReference, IEnumerable<GetChildrenReferenceResult> children, CacheSettings cacheSettings) { // Set a low cache setting so new items are fetched from data source, but keep the // items already fetched for a long time in the cache. cacheSettings.SlidingExpiration = TimeSpan.FromSeconds(120); base.SetCacheSettings(contentReference, children, cacheSettings); } #endregion } public class RSSPage { public string Guid { get; set; } public string Title { get; set; } public string Description { get; set; } public string Content { get; set; } public DateTime PubDate { get; set; } public string Language { get; set; } public string DocumentUrl { get; set; } } public static class Extensions { public static T GetValue<T>(this XElement element, string name) { if (element.Element(name) == null) { return default(T); } try { return (T)Convert.ChangeType(element.Element(name).Value, typeof(T)); } catch (Exception) { return default(T); } } public static T GetAttributeFromElement<T>(this XElement element, string elementName, string attributeName) { if (element.Element(elementName) == null) { return default(T); } try { if (element.Element(elementName).HasAttributes && element.Element(elementName).Attribute(attributeName) != null) { } return (T)Convert.ChangeType(element.Element(elementName).Attribute(attributeName).Value, typeof(T)); } catch (Exception) { return default(T); } } } } |
Find the code also on gist github: https://gist.github.com/LucGosso/
This blogpost is a continuation of a series of blog posts on Content Providers, former Page Provider for EPiServer:
Contentprovider example for #EPiServer, Former PageProvider, Part one