-
-
Save MichaelaIvanova/8edf5ff085bb685beb127afaf4069e01 to your computer and use it in GitHub Desktop.
Fake an UmbracoContext for use when doing published scheduling or other scenarios where UmbracoContext is normally null.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ContextHelpers | |
{ | |
public static UmbracoContext EnsureUmbracoContext() { | |
if (UmbracoContext.Current != null) | |
{ | |
return UmbracoContext.Current; | |
} | |
var httpContext = new HttpContextWrapper(HttpContext.Current ?? new HttpContext(new SimpleWorkerRequest("temp.aspx", "", new StringWriter()))); | |
/* v7.3+ */ | |
return UmbracoContext.EnsureContext( | |
httpContext, | |
ApplicationContext.Current, | |
new WebSecurity(httpContext, ApplicationContext.Current), | |
UmbracoConfig.For.UmbracoSettings(), | |
UrlProviderResolver.Current.Providers, | |
false); | |
/* v6.1.4 - v7.2.8 */ | |
return UmbracoContext.EnsureContext(httpContext, ApplicationContext.Current, new WebSecurity(httpContext, ApplicationContext.Current), false); | |
/* v6.1.3 and earlier (I think) */ | |
return (typeof(UmbracoContext) | |
.GetMethods(BindingFlags.Static | BindingFlags.NonPublic) | |
.First(x => x.GetParameters().Count() == 3) | |
.Invoke(null, new object[] { httpContext, ApplicationContext.Current, false })) as UmbracoContext; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EventHooks : ApplicationEventHandler | |
{ | |
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ | |
base.ApplicationStarted(umbracoApplication, applicationContext); | |
Umbraco.Core.Services.ContentService.Published += (sender, args) => | |
{ | |
using (var umbracoContext = SiteHelpers.EnsureUmbracoContext()) | |
{ | |
var helper = new UmbracoHelper(umbracoContext); | |
foreach (var content in args.PublishedEntities) | |
{ | |
var publishedContent = helper.TypedContent(content.Id); | |
var url = publishedContent.Url; | |
// do something with that url | |
... | |
} | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment