Merge branch '1.9.x' into dev

Conflicts:
	src/Orchard.Web/Modules/Orchard.Autoroute/Drivers/AutoroutePartDriver.cs
	src/Orchard.Web/Modules/Orchard.Autoroute/Migrations.cs
	src/Orchard.Web/Modules/Orchard.Search/Drivers/AdminSearchSettingsPartDriver.cs
	src/Orchard/Environment/DefaultOrchardShell.cs
	src/Orchard/Mvc/HttpContextAccessor.cs
	src/Orchard/Orchard.Framework.csproj
	src/Orchard/Tasks/BackgroundService.cs
This commit is contained in:
Sebastien Ros
2015-09-04 13:15:43 -07:00
86 changed files with 679 additions and 538 deletions
@@ -303,5 +303,24 @@ namespace Orchard.Tests.Modules.Indexing {
_provider.Store("default", _provider.New(1).Add("field", "value2"));
Assert.That(searchBuilder.WithField("id", "1").Count(), Is.EqualTo(1));
}
[Test]
public void IndexProviderShouldDeleteMoreThanMaxTermsCount() {
_provider.CreateIndex("default");
var documents = Enumerable.Range(1, 1025).Select(i => _provider.New(i).Add("field", "value1"));
_provider.Store("default", documents);
var searchBuilder = _provider.CreateSearchBuilder("default");
Assert.That(searchBuilder.Count(), Is.EqualTo(1025));
Assert.That(searchBuilder.Get(1).ContentItemId, Is.EqualTo(1));
Assert.That(searchBuilder.Get(1025).ContentItemId, Is.EqualTo(1025));
_provider.Delete("default", Enumerable.Range(1, 1025));
Assert.That(searchBuilder.Count(), Is.EqualTo(0));
}
}
}
@@ -28,13 +28,6 @@ namespace Orchard.Tests.Environment {
container.Mock<IHttpContextAccessor>()
.Setup(x => x.Current())
.Returns(() => _httpContextCurrent);
container.Mock<IHttpContextAccessor>()
.Setup(x => x.CreateContext(It.IsAny<ILifetimeScope>()))
.Returns(() => new StubHttpContext());
container.Mock<IWorkContextEvents>()
.Setup(x => x.Started());
}
[Test]
@@ -56,11 +56,7 @@ namespace Orchard.Tests.Environment.ShellBuilders {
_container.Mock<IHttpContextAccessor>()
.Setup(x => x.Current())
.Returns(httpContext);
_container.Mock<IHttpContextAccessor>()
.Setup(x => x.CreateContext(It.IsAny<ILifetimeScope>()))
.Returns(httpContext);
.Returns(default(HttpContextBase));
var factory = _container.Resolve<IShellContextFactory>();
@@ -43,10 +43,6 @@ namespace Orchard.Tests.Environment.State {
_container.Mock<IHttpContextAccessor>()
.Setup(x=>x.Current())
.Returns(httpContext);
_container.Mock<IHttpContextAccessor>()
.Setup(x => x.CreateContext(It.IsAny<ILifetimeScope>()))
.Returns(httpContext);
}
[TearDown]
@@ -1,5 +1,4 @@
using System.Web;
using Autofac;
using Orchard.Mvc;
namespace Orchard.Tests.Stubs {
@@ -17,10 +16,6 @@ namespace Orchard.Tests.Stubs {
return _httpContext;
}
public HttpContextBase CreateContext(ILifetimeScope lifetimeScope) {
return _httpContext;
}
public void Set(HttpContextBase httpContext) {
_httpContext = httpContext;
}
@@ -23,10 +23,6 @@ namespace Orchard.Tests.Tasks {
.Setup(x => x.Current())
.Returns(() => null);
container.Mock<IHttpContextAccessor>()
.Setup(x => x.CreateContext(It.IsAny<ILifetimeScope>()))
.Returns(() => new StubHttpContext());
container.Mock<IWorkContextEvents>()
.Setup(x => x.Started());
}
@@ -61,10 +61,14 @@ namespace Orchard.Core.Common.Drivers {
}
protected override void Importing(BodyPart part, ContentManagement.Handlers.ImportContentContext context) {
var importedText = context.Attribute(part.PartDefinition.Name, "Text");
if (importedText != null) {
part.Text = importedText;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Text", importedText =>
part.Text = importedText
);
}
protected override void Exporting(BodyPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -68,35 +68,35 @@ namespace Orchard.Core.Common.Drivers {
}
protected override void Importing(CommonPart part, ImportContentContext context) {
var owner = context.Attribute(part.PartDefinition.Name, "Owner");
if (owner != null) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Owner", owner => {
var contentIdentity = new ContentIdentity(owner);
part.Owner = _membershipService.GetUser(contentIdentity.Get("User.UserName"));
}
// use the super user if the referenced one doesn't exist
else {
part.Owner = _membershipService.GetUser(Services.WorkContext.CurrentSite.SuperUser);
}
var container = context.Attribute(part.PartDefinition.Name, "Container");
if (container != null) {
part.Container = context.GetItemFromSession(container);
}
// use the super user if the referenced one doesn't exist;
part.Owner =
_membershipService.GetUser(contentIdentity.Get("User.UserName"))
?? _membershipService.GetUser(Services.WorkContext.CurrentSite.SuperUser);
});
var createdUtc = context.Attribute(part.PartDefinition.Name, "CreatedUtc");
if (createdUtc != null) {
part.CreatedUtc = XmlConvert.ToDateTime(createdUtc, XmlDateTimeSerializationMode.Utc);
}
context.ImportAttribute(part.PartDefinition.Name, "Container", container =>
part.Container = context.GetItemFromSession(container)
);
var publishedUtc = context.Attribute(part.PartDefinition.Name, "PublishedUtc");
if (publishedUtc != null) {
part.PublishedUtc = XmlConvert.ToDateTime(publishedUtc, XmlDateTimeSerializationMode.Utc);
}
context.ImportAttribute(part.PartDefinition.Name, "CreatedUtc", createdUtc =>
part.CreatedUtc = XmlConvert.ToDateTime(createdUtc, XmlDateTimeSerializationMode.Utc)
);
var modifiedUtc = context.Attribute(part.PartDefinition.Name, "ModifiedUtc");
if (modifiedUtc != null) {
part.ModifiedUtc = XmlConvert.ToDateTime(modifiedUtc, XmlDateTimeSerializationMode.Utc);
}
context.ImportAttribute(part.PartDefinition.Name, "PublishedUtc", publishedUtc =>
part.PublishedUtc = XmlConvert.ToDateTime(publishedUtc, XmlDateTimeSerializationMode.Utc)
);
context.ImportAttribute(part.PartDefinition.Name, "ModifiedUtc", modifiedUtc =>
part.ModifiedUtc = XmlConvert.ToDateTime(modifiedUtc, XmlDateTimeSerializationMode.Utc)
);
}
protected override void Exporting(CommonPart part, ExportContentContext context) {
@@ -15,10 +15,14 @@ namespace Orchard.Core.Common.Drivers {
}
protected override void Importing(IdentityPart part, ContentManagement.Handlers.ImportContentContext context) {
var identity = context.Attribute(part.PartDefinition.Name, "Identifier");
if (identity != null) {
part.Identifier = identity;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Identifier", identity =>
part.Identifier = identity
);
}
protected override void Exporting(IdentityPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -82,6 +82,11 @@ namespace Orchard.Core.Containers.Drivers {
}
protected override void Importing(ContainablePart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Position", s => part.Position = XmlConvert.ToInt32(s));
}
@@ -129,12 +129,16 @@ namespace Orchard.Core.Containers.Drivers {
}
protected override void Importing(ContainerPart part, ImportContentContext context) {
var itemContentType = context.Attribute(part.PartDefinition.Name, "ItemContentTypes");
if (itemContentType != null) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "ItemContentTypes", itemContentType => {
if (_contentDefinitionManager.GetTypeDefinition(itemContentType) != null) {
part.Record.ItemContentTypes = itemContentType;
}
}
});
context.ImportAttribute(part.PartDefinition.Name, "ItemsShown", s => part.ItemsShown = XmlConvert.ToBoolean(s));
context.ImportAttribute(part.PartDefinition.Name, "Paginated", s => part.Paginated = XmlConvert.ToBoolean(s));
@@ -81,23 +81,25 @@ namespace Orchard.Core.Containers.Drivers {
}
protected override void Importing(ContainerWidgetPart part, ImportContentContext context) {
var containerIdentity = context.Attribute(part.PartDefinition.Name, "Container");
if (containerIdentity != null) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Container", containerIdentity => {
var container = context.GetItemFromSession(containerIdentity);
if (container != null) {
part.Record.ContainerId = container.Id;
}
}
});
var pageSize = context.Attribute(part.PartDefinition.Name, "PageSize");
if (pageSize != null) {
part.Record.PageSize = Convert.ToInt32(pageSize);
}
context.ImportAttribute(part.PartDefinition.Name, "PageSize", pageSize =>
part.Record.PageSize = Convert.ToInt32(pageSize)
);
var filterByValue = context.Attribute(part.PartDefinition.Name, "FilterByValue");
if (filterByValue != null) {
part.Record.FilterByValue = filterByValue;
}
context.ImportAttribute(part.PartDefinition.Name, "FilterByValue", filterByValue =>
part.Record.FilterByValue = filterByValue
);
}
protected override void Exporting(ContainerWidgetPart part, ExportContentContext context) {
@@ -24,20 +24,22 @@ namespace Orchard.Core.Containers.Drivers {
}
protected override void Importing(CustomPropertiesPart part, ImportContentContext context) {
var customOne = context.Attribute(part.PartDefinition.Name, "CustomOne");
if (customOne != null) {
part.Record.CustomOne = customOne;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var customTwo = context.Attribute(part.PartDefinition.Name, "CustomTwo");
if (customTwo != null) {
part.Record.CustomTwo = customTwo;
}
context.ImportAttribute(part.PartDefinition.Name, "CustomOne", customOne =>
part.Record.CustomOne = customOne
);
var customThree = context.Attribute(part.PartDefinition.Name, "CustomThree");
if (customThree != null) {
part.Record.CustomThree = customThree;
}
context.ImportAttribute(part.PartDefinition.Name, "CustomTwo", customTwo =>
part.Record.CustomTwo = customTwo
);
context.ImportAttribute(part.PartDefinition.Name, "CustomThree", customThree =>
part.Record.CustomThree = customThree
);
}
protected override void Exporting(CustomPropertiesPart part, ExportContentContext context) {
@@ -71,20 +71,22 @@ namespace Orchard.Core.Navigation.Drivers {
}
protected override void Importing(AdminMenuPart part, ContentManagement.Handlers.ImportContentContext context) {
var adminMenuText = context.Attribute(part.PartDefinition.Name, "AdminMenuText");
if (adminMenuText != null) {
part.AdminMenuText = adminMenuText;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var position = context.Attribute(part.PartDefinition.Name, "AdminMenuPosition");
if (position != null) {
part.AdminMenuPosition = position;
}
context.ImportAttribute(part.PartDefinition.Name, "AdminMenuText", adminMenuText =>
part.AdminMenuText = adminMenuText
);
var onAdminMenu = context.Attribute(part.PartDefinition.Name, "OnAdminMenu");
if (onAdminMenu != null) {
part.OnAdminMenu = Convert.ToBoolean(onAdminMenu);
}
context.ImportAttribute(part.PartDefinition.Name, "AdminMenuPosition", position =>
part.AdminMenuPosition = position
);
context.ImportAttribute(part.PartDefinition.Name, "OnAdminMenu", onAdminMenu =>
part.OnAdminMenu = Convert.ToBoolean(onAdminMenu)
);
}
protected override void Exporting(AdminMenuPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -35,10 +35,14 @@ namespace Orchard.Core.Navigation.Drivers {
}
protected override void Importing(MenuItemPart part, ContentManagement.Handlers.ImportContentContext context) {
var url = context.Attribute(part.PartDefinition.Name, "Url");
if (url != null) {
part.Url = url;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Url", url =>
part.Url = url
);
}
protected override void Exporting(MenuItemPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -80,23 +80,25 @@ namespace Orchard.Core.Navigation.Drivers {
}
protected override void Importing(MenuPart part, ContentManagement.Handlers.ImportContentContext context) {
var menuText = context.Attribute(part.PartDefinition.Name, "MenuText");
if (menuText != null) {
part.MenuText = menuText;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var position = context.Attribute(part.PartDefinition.Name, "MenuPosition");
if (position != null) {
part.MenuPosition = position;
}
context.ImportAttribute(part.PartDefinition.Name, "MenuText", menuText =>
part.MenuText = menuText
);
var menuIdentity = context.Attribute(part.PartDefinition.Name, "Menu");
if (menuIdentity != null) {
context.ImportAttribute(part.PartDefinition.Name, "MenuPosition", position =>
part.MenuPosition = position
);
context.ImportAttribute(part.PartDefinition.Name, "Menu", menuIdentity => {
var menu = context.GetItemFromSession(menuIdentity);
if (menu != null) {
part.Menu = menu;
}
}
});
}
protected override void Exporting(MenuPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -190,6 +190,11 @@ namespace Orchard.Core.Navigation.Drivers {
}
protected override void Importing(MenuWidgetPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "StartLevel", x => part.StartLevel = Convert.ToInt32(x));
context.ImportAttribute(part.PartDefinition.Name, "Levels", x => part.Levels = Convert.ToInt32(x));
context.ImportAttribute(part.PartDefinition.Name, "Breadcrumb", x => part.Breadcrumb = Convert.ToBoolean(x));
@@ -37,13 +37,12 @@ namespace Orchard.Core.Navigation.Drivers {
}
protected override void Importing(ShapeMenuItemPart part, ImportContentContext context) {
IfNotNull(context.Attribute(part.PartDefinition.Name, "ShapeType"), x => part.ShapeType = x);
}
private static void IfNotNull<T>(T value, Action<T> then) where T : class {
if(value != null) {
then(value);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "ShapeType", x => part.ShapeType = x);
}
protected override void Exporting(ShapeMenuItemPart part, ExportContentContext context) {
@@ -116,12 +116,16 @@ namespace Orchard.Core.Settings.Drivers {
}
protected override void Importing(SiteSettingsPart part, ContentManagement.Handlers.ImportContentContext context) {
var supportedCultures = context.Attribute(part.PartDefinition.Name, "SupportedCultures");
if (supportedCultures != null) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "SupportedCultures", supportedCultures => {
foreach (var culture in supportedCultures.Split(';')) {
_cultureManager.AddCulture(culture);
}
}
});
}
}
}
@@ -39,10 +39,14 @@ namespace Orchard.Core.Title.Drivers {
}
protected override void Importing(TitlePart part, ImportContentContext context) {
var title = context.Attribute(part.PartDefinition.Name, "Title");
if (title != null) {
part.Title = title;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Title", title =>
part.Title = title
);
}
protected override void Exporting(TitlePart part, ExportContentContext context) {
@@ -29,7 +29,8 @@ namespace Lucene.Services {
public static readonly Version LuceneVersion = Version.LUCENE_29;
public static readonly DateTime DefaultMinDateTime = new DateTime(1980, 1, 1);
public static readonly int BatchSize = BooleanQuery.MaxClauseCount;
public LuceneIndexProvider(
IAppDataFolder appDataFolder,
ShellSettings shellSettings,
@@ -152,17 +153,25 @@ namespace Lucene.Services {
}
using (var writer = new IndexWriter(GetDirectory(indexName), _analyzerProvider.GetAnalyzer(indexName), false, IndexWriter.MaxFieldLength.UNLIMITED)) {
var query = new BooleanQuery();
// Process documents by batch as there is a max number of terms a query can contain (1024 by default).
var pageCount = documentIds.Count() / BatchSize + 1;
for (int page = 0; page < pageCount; page++) {
var query = new BooleanQuery();
try {
foreach (var id in documentIds) {
query.Add(new BooleanClause(new TermQuery(new Term("id", id.ToString(CultureInfo.InvariantCulture))), Occur.SHOULD));
try {
var batch = documentIds
.Skip(page * BatchSize)
.Take(BatchSize);
foreach (var id in batch) {
query.Add(new BooleanClause(new TermQuery(new Term("id", id.ToString(CultureInfo.InvariantCulture))), Occur.SHOULD));
}
writer.DeleteDocuments(query);
}
catch (Exception ex) {
Logger.Error(ex, "An unexpected error occured while removing the documents [{0}] from the index [{1}].", String.Join(", ", documentIds), indexName);
}
writer.DeleteDocuments(query);
}
catch (Exception ex) {
Logger.Error(ex, "An unexpected error occured while removing the documents [{0}] from the index [{1}].", String.Join(", ", documentIds), indexName);
}
}
}
@@ -1,7 +1,4 @@
using System;
using System.Linq;
using Orchard.Alias.Implementation.Holder;
using Orchard.Alias.Implementation.Storage;
using Orchard.Environment;
using Orchard.Tasks;
using Orchard.Logging;
@@ -42,6 +42,11 @@ namespace Orchard.AntiSpam.Drivers {
}
protected override void Importing(SpamFilterPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var status = context.Attribute(part.PartDefinition.Name, "Status");
if (status != null) {
@@ -92,10 +92,14 @@ namespace Orchard.ArchiveLater.Drivers {
}
protected override void Importing(ArchiveLaterPart part, ImportContentContext context) {
var scheduledUtc = context.Attribute(part.PartDefinition.Name, "ScheduledArchiveUtc");
if (scheduledUtc != null) {
part.ScheduledArchiveUtc.Value = XmlConvert.ToDateTime(scheduledUtc, XmlDateTimeSerializationMode.Utc);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "ScheduledArchiveUtc", scheduledUtc =>
part.ScheduledArchiveUtc.Value = XmlConvert.ToDateTime(scheduledUtc, XmlDateTimeSerializationMode.Utc)
);
}
protected override void Exporting(ArchiveLaterPart part, ExportContentContext context) {
@@ -154,6 +154,11 @@ namespace Orchard.Autoroute.Drivers {
}
protected override void Importing(AutoroutePart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Alias", s => part.DisplayAlias = s);
context.ImportAttribute(part.PartDefinition.Name, "CustomPattern", s => part.CustomPattern = s);
context.ImportAttribute(part.PartDefinition.Name, "UseCustomPattern", s => part.UseCustomPattern = XmlHelper.Parse<bool>(s));
@@ -1,4 +1,5 @@
using Orchard.Autoroute.Models;
using Orchard.ContentManagement;
using Orchard.Autoroute.Services;
using Orchard.Autoroute.Settings;
using Orchard.ContentManagement;
@@ -53,10 +53,14 @@ namespace Orchard.Blogs.Drivers {
}
protected override void Importing(BlogArchivesPart part, ImportContentContext context) {
var blog = context.Attribute(part.PartDefinition.Name, "Blog");
if (blog != null) {
part.BlogId = context.GetItemFromSession(blog).Id;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Blog", blog =>
part.BlogId = context.GetItemFromSession(blog).Id
);
}
protected override void Exporting(BlogArchivesPart part, ExportContentContext context) {
@@ -43,20 +43,22 @@ namespace Orchard.Blogs.Drivers {
}
protected override void Importing(BlogPart part, ContentManagement.Handlers.ImportContentContext context) {
var description = context.Attribute(part.PartDefinition.Name, "Description");
if (description != null) {
part.Description = description;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var postCount = context.Attribute(part.PartDefinition.Name, "PostCount");
if (postCount != null) {
part.PostCount = Convert.ToInt32(postCount);
}
context.ImportAttribute(part.PartDefinition.Name, "Description", description =>
part.Description = description
);
var feedProxyUrl = context.Attribute(part.PartDefinition.Name, "FeedProxyUrl");
if (feedProxyUrl != null) {
part.FeedProxyUrl = feedProxyUrl;
}
context.ImportAttribute(part.PartDefinition.Name, "PostCount", postCount =>
part.PostCount = Convert.ToInt32(postCount)
);
context.ImportAttribute(part.PartDefinition.Name, "FeedProxyUrl", feedProxyUrl =>
part.FeedProxyUrl = feedProxyUrl
);
}
protected override void Exporting(BlogPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -66,22 +66,25 @@ namespace Orchard.Blogs.Drivers {
}
protected override void Importing(RecentBlogPostsPart part, ImportContentContext context) {
var blog = context.Attribute(part.PartDefinition.Name, "Blog");
if (blog != null) {
part.BlogId = context.GetItemFromSession(blog).Id;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var count = context.Attribute(part.PartDefinition.Name, "Count");
if (count != null) {
part.Count = Convert.ToInt32(count);
}
context.ImportAttribute(part.PartDefinition.Name, "Blog", blog =>
part.BlogId = context.GetItemFromSession(blog).Id
);
context.ImportAttribute(part.PartDefinition.Name, "Count", count =>
part.Count = Convert.ToInt32(count)
);
}
protected override void Exporting(RecentBlogPostsPart part, ExportContentContext context) {
var blog = _contentManager.Get(part.BlogId);
var blogIdentity = _contentManager.GetItemMetadata(blog).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("Blog", blogIdentity);
context.Element(part.PartDefinition.Name).SetAttributeValue("Blog", blogIdentity);
context.Element(part.PartDefinition.Name).SetAttributeValue("Count", part.Count);
}
}
@@ -132,71 +132,65 @@ namespace Orchard.Comments.Drivers {
}
protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) {
var author = context.Attribute(part.PartDefinition.Name, "Author");
if (author != null) {
part.Record.Author = author;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var siteName = context.Attribute(part.PartDefinition.Name, "SiteName");
if (siteName != null) {
part.Record.SiteName = siteName;
}
context.ImportAttribute(part.PartDefinition.Name, "Author", author =>
part.Record.Author = author
);
var userName = context.Attribute(part.PartDefinition.Name, "UserName");
if (userName != null) {
part.Record.UserName = userName;
}
context.ImportAttribute(part.PartDefinition.Name, "SiteName", siteName =>
part.Record.SiteName = siteName
);
var email = context.Attribute(part.PartDefinition.Name, "Email");
if (email != null) {
part.Record.Email = email;
}
context.ImportAttribute(part.PartDefinition.Name, "UserName", userName =>
part.Record.UserName = userName
);
var position = context.Attribute(part.PartDefinition.Name, "Position");
if (position != null) {
part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture);
}
context.ImportAttribute(part.PartDefinition.Name, "Email", email =>
part.Record.Email = email
);
var status = context.Attribute(part.PartDefinition.Name, "Status");
if (status != null) {
part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status);
}
context.ImportAttribute(part.PartDefinition.Name, "Position", position =>
part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture)
);
var commentDate = context.Attribute(part.PartDefinition.Name, "CommentDateUtc");
if (commentDate != null) {
part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc);
}
context.ImportAttribute(part.PartDefinition.Name, "Status", status =>
part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status)
);
var text = context.Attribute(part.PartDefinition.Name, "CommentText");
if (text != null) {
part.Record.CommentText = text;
}
context.ImportAttribute(part.PartDefinition.Name, "CommentDateUtc", commentDate =>
part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc)
);
var commentedOn = context.Attribute(part.PartDefinition.Name, "CommentedOn");
if (commentedOn != null) {
context.ImportAttribute(part.PartDefinition.Name, "CommentText", text =>
part.Record.CommentText = text
);
context.ImportAttribute(part.PartDefinition.Name, "CommentedOn", commentedOn => {
var contentItem = context.GetItemFromSession(commentedOn);
if (contentItem != null) {
part.Record.CommentedOn = contentItem.Id;
}
contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record);
}
});
var repliedOn = context.Attribute(part.PartDefinition.Name, "RepliedOn");
if (repliedOn != null) {
context.ImportAttribute(part.PartDefinition.Name, "RepliedOn", repliedOn => {
var contentItem = context.GetItemFromSession(repliedOn);
if (contentItem != null) {
part.Record.RepliedOn = contentItem.Id;
}
}
});
var commentedOnContainer = context.Attribute(part.PartDefinition.Name, "CommentedOnContainer");
if (commentedOnContainer != null) {
context.ImportAttribute(part.PartDefinition.Name, "CommentedOnContainer", commentedOnContainer => {
var container = context.GetItemFromSession(commentedOnContainer);
if (container != null) {
part.Record.CommentedOnContainer = container.Id;
}
}
});
}
protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -111,20 +111,22 @@ namespace Orchard.Comments.Drivers {
}
protected override void Importing(CommentsPart part, ContentManagement.Handlers.ImportContentContext context) {
var commentsShown = context.Attribute(part.PartDefinition.Name, "CommentsShown");
if (commentsShown != null) {
part.CommentsShown = Convert.ToBoolean(commentsShown);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var commentsActive = context.Attribute(part.PartDefinition.Name, "CommentsActive");
if (commentsActive != null) {
part.CommentsActive = Convert.ToBoolean(commentsActive);
}
context.ImportAttribute(part.PartDefinition.Name, "CommentsShown", commentsShown =>
part.CommentsShown = Convert.ToBoolean(commentsShown)
);
var threadedComments = context.Attribute(part.PartDefinition.Name, "ThreadedComments");
if (threadedComments != null) {
part.ThreadedComments = Convert.ToBoolean(threadedComments);
}
context.ImportAttribute(part.PartDefinition.Name, "CommentsActive", commentsActive =>
part.CommentsActive = Convert.ToBoolean(commentsActive)
);
context.ImportAttribute(part.PartDefinition.Name, "ThreadedComments", threadedComments =>
part.ThreadedComments = Convert.ToBoolean(threadedComments)
);
}
protected override void Exporting(CommentsPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -162,6 +162,11 @@ namespace Orchard.ContentPermissions.Drivers {
}
protected override void Importing(ContentPermissionsPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Enabled", s => part.Enabled = XmlConvert.ToBoolean(s));
context.ImportAttribute(part.PartDefinition.Name, "ViewContent", s => part.ViewContent = s);
context.ImportAttribute(part.PartDefinition.Name, "EditContent", s => part.EditContent = s);
@@ -60,14 +60,18 @@ namespace Orchard.ContentPicker.Drivers {
}
protected override void Importing(ContentMenuItemPart part, ImportContentContext context) {
var contentItemId = context.Attribute(part.PartDefinition.Name, "ContentItem");
if (contentItemId != null) {
var contentItem = context.GetItemFromSession(contentItemId);
part.Content = contentItem;
}
else {
part.Content = null;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "ContentItem",
contentItemId => {
var contentItem = context.GetItemFromSession(contentItemId);
part.Content = contentItem;
}, () =>
part.Content = null
);
}
protected override void Exporting(ContentMenuItemPart part, ExportContentContext context) {
@@ -59,21 +59,20 @@ namespace Orchard.CustomForms.Drivers {
}
protected override void Importing(CustomFormPart part, ImportContentContext context) {
IfNotNull(context.Attribute(part.PartDefinition.Name, "ContentType"), x => part.Record.ContentType = x);
IfNotNull(context.Attribute(part.PartDefinition.Name, "SaveContentItem"), x => part.Record.SaveContentItem = Boolean.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "CustomMessage"), x => part.Record.CustomMessage = Boolean.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "Message"), x => part.Record.Message = x);
IfNotNull(context.Attribute(part.PartDefinition.Name, "Redirect"), x => part.Record.Redirect = Boolean.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "RedirectUrl"), x => part.Record.RedirectUrl = x);
IfNotNull(context.Attribute(part.PartDefinition.Name, "SubmitButtonText"), x => part.Record.SubmitButtonText = x);
}
private static void IfNotNull<T>(T value, Action<T> then) {
if (value != null) {
then(value);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
}
context.ImportAttribute(part.PartDefinition.Name, "ContentType", x => part.Record.ContentType = x);
context.ImportAttribute(part.PartDefinition.Name, "SaveContentItem", x => part.Record.SaveContentItem = Boolean.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "CustomMessage", x => part.Record.CustomMessage = Boolean.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "Message", x => part.Record.Message = x);
context.ImportAttribute(part.PartDefinition.Name, "Redirect", x => part.Record.Redirect = Boolean.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "RedirectUrl", x => part.Record.RedirectUrl = x);
context.ImportAttribute(part.PartDefinition.Name, "SubmitButtonText", x => part.Record.SubmitButtonText = x);
}
protected override void Exporting(CustomFormPart part, ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("ContentType", part.Record.ContentType);
context.Element(part.PartDefinition.Name).SetAttributeValue("SaveContentItem", part.Record.SaveContentItem);
@@ -140,6 +140,11 @@ namespace Orchard.Layouts.Drivers {
}
protected override void Importing(LayoutPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportChildEl(part.PartDefinition.Name, "LayoutData", s => {
part.LayoutData = s;
_layoutManager.Importing(new ImportLayoutContext {
@@ -290,11 +290,11 @@ namespace Orchard.Layouts.Drivers {
var query = element.QueryId != null ? _contentManager.Get<QueryPart>(element.QueryId.Value) : default(QueryPart);
var layout = query != null && element.LayoutId != null ? _layoutRepository.Get(element.LayoutId.Value) : default(LayoutRecord);
var queryIdentity = query != null ? _contentManager.GetItemMetadata(query).Identity.ToString() : default(string);
var layoutIndex = layout != null ? query.Layouts.IndexOf(layout) : default(int?);
var layoutIndex = layout != null ? query.Layouts.IndexOf(layout) : -1; // -1 is the Default Layout.
if (queryIdentity != null && layoutIndex != null) {
if (queryIdentity != null) {
context.ExportableData["QueryId"] = queryIdentity;
context.ExportableData["LayoutIndex"] = layoutIndex.Value.ToString();
context.ExportableData["LayoutIndex"] = layoutIndex.ToString();
}
}
@@ -16,7 +16,6 @@ namespace Orchard.Layouts.Handlers {
private readonly IContentPartDisplay _contentPartDisplay;
private readonly IShapeDisplay _shapeDisplay;
private readonly ILayoutSerializer _serializer;
private readonly IStaticHttpContextScopeFactory _staticHttpContextScopeFactory;
private readonly IAliasService _aliasService;
public LayoutPartHandler(
@@ -26,7 +25,6 @@ namespace Orchard.Layouts.Handlers {
IContentPartDisplay contentPartDisplay,
IShapeDisplay shapeDisplay,
ILayoutSerializer serializer,
IStaticHttpContextScopeFactory staticHttpContextScopeFactory,
IAliasService aliasService) {
_layoutManager = layoutManager;
@@ -34,7 +32,6 @@ namespace Orchard.Layouts.Handlers {
_contentPartDisplay = contentPartDisplay;
_shapeDisplay = shapeDisplay;
_serializer = serializer;
_staticHttpContextScopeFactory = staticHttpContextScopeFactory;
_aliasService = aliasService;
Filters.Add(StorageFilter.For(repository));
@@ -44,22 +41,13 @@ namespace Orchard.Layouts.Handlers {
private void IndexLayout(IndexContentContext context, LayoutPart part) {
var layoutShape = _contentPartDisplay.BuildDisplay(part);
var layoutHtml = RenderShape(layoutShape);
var layoutHtml = _shapeDisplay.Display(layoutShape);
context.DocumentIndex
.Add("body", layoutHtml).RemoveTags().Analyze()
.Add("format", "html").Store();
}
/// <summary>
/// This method of rendering is safe even in background tasks.
/// </summary>
private string RenderShape(dynamic shape) {
using (_staticHttpContextScopeFactory.CreateStaticScope()) {
return _shapeDisplay.Display(shape);
}
}
private void UpdateTemplateClients(PublishContentContext context, LayoutPart part) {
UpdateTemplateClients(part);
}
@@ -108,16 +108,19 @@ namespace Orchard.Localization.Drivers {
}
protected override void Importing(LocalizationPart part, ContentManagement.Handlers.ImportContentContext context) {
var masterContentItem = context.Attribute(part.PartDefinition.Name, "MasterContentItem");
if (masterContentItem != null) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "MasterContentItem", masterContentItem => {
var contentItem = context.GetItemFromSession(masterContentItem);
if (contentItem != null) {
part.MasterContentItem = contentItem;
}
}
});
var culture = context.Attribute(part.PartDefinition.Name, "Culture");
if (culture != null) {
context.ImportAttribute(part.PartDefinition.Name, "Culture", culture => {
var targetCulture = _cultureManager.GetCultureByName(culture);
// Add Culture.
if (targetCulture == null && _cultureManager.IsValidCulture(culture)) {
@@ -125,7 +128,7 @@ namespace Orchard.Localization.Drivers {
targetCulture = _cultureManager.GetCultureByName(culture);
}
part.Culture = targetCulture;
}
});
}
protected override void Exporting(LocalizationPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -17,10 +17,14 @@ namespace Orchard.MediaLibrary.Drivers {
}
protected override void Importing(AudioPart part, ContentManagement.Handlers.ImportContentContext context) {
var length = context.Attribute(part.PartDefinition.Name, "Length");
if (length != null) {
part.Length = int.Parse(length);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Length", length =>
part.Length = int.Parse(length)
);
}
}
}
@@ -17,10 +17,14 @@ namespace Orchard.MediaLibrary.Drivers {
}
protected override void Importing(DocumentPart part, ContentManagement.Handlers.ImportContentContext context) {
var length = context.Attribute(part.PartDefinition.Name, "Length");
if (length != null) {
part.Length = int.Parse(length);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Length", length =>
part.Length = int.Parse(length)
);
}
}
}
@@ -20,15 +20,18 @@ namespace Orchard.MediaLibrary.Drivers {
}
protected override void Importing(ImagePart part, ContentManagement.Handlers.ImportContentContext context) {
var height = context.Attribute(part.PartDefinition.Name, "Height");
if (height != null) {
part.Height = int.Parse(height);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var width = context.Attribute(part.PartDefinition.Name, "Width");
if (width != null) {
part.Width = int.Parse(width);
}
context.ImportAttribute(part.PartDefinition.Name, "Height", height =>
part.Height = int.Parse(height)
);
context.ImportAttribute(part.PartDefinition.Name, "Width", width =>
part.Width = int.Parse(width)
);
}
}
}
@@ -36,30 +36,30 @@ namespace Orchard.MediaLibrary.Drivers {
}
protected override void Importing(MediaPart part, ContentManagement.Handlers.ImportContentContext context) {
var mimeType = context.Attribute(part.PartDefinition.Name, "MimeType");
if (mimeType != null) {
part.MimeType = mimeType;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var caption = context.Attribute(part.PartDefinition.Name, "Caption");
if (caption != null) {
part.Caption = caption;
}
context.ImportAttribute(part.PartDefinition.Name, "MimeType", mimeType =>
part.MimeType = mimeType
);
var alternateText = context.Attribute(part.PartDefinition.Name, "AlternateText");
if (alternateText != null) {
part.AlternateText = alternateText;
}
context.ImportAttribute(part.PartDefinition.Name, "Caption", caption =>
part.Caption = caption
);
var folderPath = context.Attribute(part.PartDefinition.Name, "FolderPath");
if (folderPath != null) {
part.FolderPath = folderPath;
}
context.ImportAttribute(part.PartDefinition.Name, "AlternateText", alternateText =>
part.AlternateText = alternateText
);
var fileName = context.Attribute(part.PartDefinition.Name, "FileName");
if (fileName != null) {
part.FileName = fileName;
}
context.ImportAttribute(part.PartDefinition.Name, "FolderPath", folderPath =>
part.FolderPath = folderPath
);
context.ImportAttribute(part.PartDefinition.Name, "FileName", fileName =>
part.FileName = fileName
);
}
protected override void Exporting(MediaPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -17,10 +17,14 @@ namespace Orchard.MediaLibrary.Drivers {
}
protected override void Importing(OEmbedPart part, ContentManagement.Handlers.ImportContentContext context) {
var source = context.Attribute(part.PartDefinition.Name, "Source");
if (source != null) {
part.Source = source;
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Source", source =>
part.Source = source
);
}
}
}
@@ -17,10 +17,14 @@ namespace Orchard.MediaLibrary.Drivers {
}
protected override void Importing(VideoPart part, ContentManagement.Handlers.ImportContentContext context) {
var length = context.Attribute(part.PartDefinition.Name, "Length");
if (length != null) {
part.Length = int.Parse(length);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Length", length =>
part.Length = int.Parse(length)
);
}
}
}
@@ -85,6 +85,11 @@ namespace Orchard.MediaProcessing.Drivers {
}
protected override void Importing(ImageProfilePart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var element = context.Data.Element(part.PartDefinition.Name);
part.Name = element.Attribute("Name").Value;
@@ -54,8 +54,13 @@ namespace Orchard.Projections.Drivers {
}
protected override void Importing(NavigationQueryPart part, ImportContentContext context) {
IfNotNull(context.Attribute(part.PartDefinition.Name, "Items"), x => part.Record.Items = Int32.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "Offset"), x => part.Record.Skip = Int32.Parse(x));
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Items", x => part.Record.Items = Int32.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "Offset", x => part.Record.Skip = Int32.Parse(x));
}
protected override void Imported(NavigationQueryPart part, ImportContentContext context) {
@@ -65,13 +70,7 @@ namespace Orchard.Projections.Drivers {
part.Record.QueryPartRecord = context.GetItemFromSession(query).As<QueryPart>().Record;
}
}
private static void IfNotNull<T>(T value, Action<T> then) where T : class {
if(value != null) {
then(value);
}
}
protected override void Exporting(NavigationQueryPart part, ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("Items", part.Record.Items);
context.Element(part.PartDefinition.Name).SetAttributeValue("Offset", part.Record.Skip);
@@ -294,12 +294,17 @@ namespace Orchard.Projections.Drivers {
}
protected override void Importing(ProjectionPart part, ImportContentContext context) {
IfNotNull(context.Attribute(part.PartDefinition.Name, "Items"), x => part.Record.Items = Int32.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "ItemsPerPage"), x => part.Record.ItemsPerPage = Int32.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "Offset"), x => part.Record.Skip = Int32.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "PagerSuffix"), x => part.Record.PagerSuffix = x);
IfNotNull(context.Attribute(part.PartDefinition.Name, "MaxItems"), x => part.Record.MaxItems = Int32.Parse(x));
IfNotNull(context.Attribute(part.PartDefinition.Name, "DisplayPager"), x => part.Record.DisplayPager = Boolean.Parse(x));
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Items", x => part.Record.Items = Int32.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "ItemsPerPage", x => part.Record.ItemsPerPage = Int32.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "Offset", x => part.Record.Skip = Int32.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "PagerSuffix", x => part.Record.PagerSuffix = x);
context.ImportAttribute(part.PartDefinition.Name, "MaxItems", x => part.Record.MaxItems = Int32.Parse(x));
context.ImportAttribute(part.PartDefinition.Name, "DisplayPager", x => part.Record.DisplayPager = Boolean.Parse(x));
}
protected override void Imported(ProjectionPart part, ImportContentContext context) {
@@ -318,13 +323,7 @@ namespace Orchard.Projections.Drivers {
}
}
}
private static void IfNotNull<T>(T value, Action<T> then) {
if(value != null) {
then(value);
}
}
protected override void Exporting(ProjectionPart part, ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("Items", part.Record.Items);
context.Element(part.PartDefinition.Name).SetAttributeValue("ItemsPerPage", part.Record.ItemsPerPage);
@@ -103,6 +103,11 @@ namespace Orchard.Projections.Drivers {
}
protected override void Importing(QueryPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var queryElement = context.Data.Element(part.PartDefinition.Name);
part.Record.FilterGroups.Clear();
@@ -110,10 +110,14 @@ namespace Orchard.PublishLater.Drivers {
}
protected override void Importing(PublishLaterPart part, ImportContentContext context) {
var scheduledUtc = context.Attribute(part.PartDefinition.Name, "ScheduledPublishUtc");
if (scheduledUtc != null) {
part.ScheduledPublishUtc.Value = XmlConvert.ToDateTime(scheduledUtc, XmlDateTimeSerializationMode.Utc);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "ScheduledPublishUtc", scheduledUtc =>
part.ScheduledPublishUtc.Value = XmlConvert.ToDateTime(scheduledUtc, XmlDateTimeSerializationMode.Utc)
);
}
protected override void Exporting(PublishLaterPart part, ExportContentContext context) {
@@ -96,29 +96,32 @@ namespace Orchard.Roles.Drivers {
}
protected override void Importing(UserRolesPart part, ContentManagement.Handlers.ImportContentContext context) {
var roles = context.Attribute(part.PartDefinition.Name, "Roles");
if(string.IsNullOrEmpty(roles)) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var userRoles = roles.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
context.ImportAttribute(part.PartDefinition.Name, "Roles", roles => {
// create new roles
foreach (var role in userRoles) {
var roleRecord = _roleService.GetRoleByName(role);
var userRoles = roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
// create the role if it doesn't already exist
if (roleRecord == null) {
_roleService.CreateRole(role);
// create new roles
foreach (var role in userRoles) {
var roleRecord = _roleService.GetRoleByName(role);
// create the role if it doesn't already exist
if (roleRecord == null) {
_roleService.CreateRole(role);
}
}
}
var currentUserRoleRecords = _userRolesRepository.Fetch(x => x.UserId == part.ContentItem.Id).ToList();
var currentRoleRecords = currentUserRoleRecords.Select(x => x.Role).ToList();
var targetRoleRecords = userRoles.Select(x => _roleService.GetRoleByName(x)).ToList();
foreach (var addingRole in targetRoleRecords.Where(x => !currentRoleRecords.Contains(x))) {
_userRolesRepository.Create(new UserRolesPartRecord { UserId = part.ContentItem.Id, Role = addingRole });
}
var currentUserRoleRecords = _userRolesRepository.Fetch(x => x.UserId == part.ContentItem.Id).ToList();
var currentRoleRecords = currentUserRoleRecords.Select(x => x.Role).ToList();
var targetRoleRecords = userRoles.Select(x => _roleService.GetRoleByName(x)).ToList();
foreach (var addingRole in targetRoleRecords.Where(x => !currentRoleRecords.Contains(x))) {
_userRolesRepository.Create(new UserRolesPartRecord { UserId = part.ContentItem.Id, Role = addingRole });
}
});
}
protected override void Exporting(UserRolesPart part, ContentManagement.Handlers.ExportContentContext context) {
@@ -1,6 +1,7 @@
using System.Linq;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Orchard.Environment.Extensions;
using Orchard.Indexing;
using Orchard.Search.Models;
@@ -37,5 +38,16 @@ namespace Orchard.Search.Drivers {
return shapeHelper.EditorTemplate(TemplateName: "Parts/AdminSearch.SiteSettings", Model: model, Prefix: Prefix);
}).OnGroup("search");
}
protected override void Importing(AdminSearchSettingsPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "SearchFields", value => {
part.Store("SearchFields", value);
});
}
}
}
}
@@ -79,15 +79,14 @@ namespace Orchard.Search.Drivers {
}
protected override void Importing(SearchSettingsPart part, ImportContentContext context) {
var xElement = context.Data.Element(part.PartDefinition.Name);
if (xElement == null) return;
var searchFields = xElement.Attribute("SearchFields");
if (searchFields != null) {
searchFields.Remove();
part.Store("SearchFields", searchFields.Value);
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "SearchFields", value => {
part.Store("SearchFields", value);
});
}
}
}
@@ -36,7 +36,6 @@ namespace Orchard.SecureSocketsLayer.Drivers {
}
protected override void Importing(SslSettingsPart part, ImportContentContext context) {
base.Importing(part, context);
_signals.Trigger(SslSettingsPart.CacheKey);
}
}
@@ -43,6 +43,11 @@ namespace Orchard.Tags.Drivers {
}
protected override void Importing(TagCloudPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
part.Slug = context.Attribute(part.PartDefinition.Name, "Slug");
part.Buckets = Convert.ToInt32(context.Attribute(part.PartDefinition.Name, "Buckets"));
}
@@ -70,6 +70,11 @@ namespace Orchard.Tags.Drivers {
}
protected override void Importing(TagsPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var tagString = context.Attribute(part.PartDefinition.Name, "Tags");
if (tagString != null) {
var tags = tagString.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
@@ -101,6 +101,11 @@ namespace Orchard.Taxonomies.Drivers {
}
protected override void Importing(TaxonomyNavigationPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
part.DisplayContentCount = Boolean.Parse(context.Attribute(part.PartDefinition.Name, "DisplayContentCount"));
part.DisplayRootTerm = Boolean.Parse(context.Attribute(part.PartDefinition.Name, "DisplayRootTerm"));
part.HideEmptyTerms = Boolean.Parse(context.Attribute(part.PartDefinition.Name, "HideEmptyTerms"));
@@ -65,6 +65,11 @@ namespace Orchard.Taxonomies.Drivers {
}
protected override void Importing(TaxonomyPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
part.TermTypeName = context.Attribute(part.PartDefinition.Name, "TermTypeName");
}
}
@@ -126,6 +126,11 @@ namespace Orchard.Taxonomies.Drivers {
}
protected override void Importing(TermPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
part.Count = Int32.Parse(context.Attribute(part.PartDefinition.Name, "Count"));
part.Selectable = Boolean.Parse(context.Attribute(part.PartDefinition.Name, "Selectable"));
part.Weight = Int32.Parse(context.Attribute(part.PartDefinition.Name, "Weight"));
@@ -58,6 +58,11 @@ namespace Orchard.Templates.Drivers {
}
protected override void Importing(ShapePart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var shapeElement = context.Data.Element(part.PartDefinition.Name);
if (shapeElement != null)
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.WebPages;
@@ -14,6 +15,7 @@ namespace Orchard.Templates.Services {
[OrchardFeature("Orchard.Templates.Razor")]
public class RazorTemplateProcessor : TemplateProcessorImpl {
private readonly IRazorCompiler _compiler;
private readonly HttpContextBase _httpContextBase;
private readonly IWorkContextAccessor _wca;
public override string Type {
@@ -22,9 +24,11 @@ namespace Orchard.Templates.Services {
public RazorTemplateProcessor(
IRazorCompiler compiler,
HttpContextBase httpContextBase,
IWorkContextAccessor wca) {
_compiler = compiler;
_httpContextBase = httpContextBase;
_wca = wca;
Logger = NullLogger.Instance;
}
@@ -37,7 +41,7 @@ namespace Orchard.Templates.Services {
public override string Process(string template, string name, DisplayContext context = null, dynamic model = null) {
if (String.IsNullOrEmpty(template))
return String.Empty;
return string.Empty;
var compiledTemplate = _compiler.CompileRazor(template, name, new Dictionary<string, object>());
var result = ActivateAndRenderTemplate(compiledTemplate, context, null, model);
@@ -69,10 +73,9 @@ namespace Orchard.Templates.Services {
// Setup a fake view context in order to support razor syntax inside of HTML attributes,
// for instance: <a href="@WorkContext.CurrentSite.BaseUrl">Homepage</a>.
var viewData = new ViewDataDictionary(model);
var httpContext = _wca.GetContext().HttpContext;
obj.ViewContext = new ViewContext(
new ControllerContext(
httpContext.Request.RequestContext,
_httpContextBase.Request.RequestContext,
new StubController()),
new StubView(),
viewData,
@@ -80,7 +83,7 @@ namespace Orchard.Templates.Services {
htmlWriter);
obj.ViewData = viewData;
obj.WebPageContext = new WebPageContext(httpContext, obj as WebPageRenderingBase, model);
obj.WebPageContext = new WebPageContext(_httpContextBase, obj as WebPageRenderingBase, model);
obj.WorkContext = _wca.GetContext();
}
@@ -11,6 +11,11 @@ namespace Orchard.Users.Drivers {
public class UserPartDriver : ContentPartDriver<UserPart> {
protected override void Importing(UserPart part, ContentManagement.Handlers.ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
part.Email = context.Attribute(part.PartDefinition.Name, "Email");
part.EmailChallengeToken = context.Attribute(part.PartDefinition.Name, "EmailChallengeToken");
part.EmailStatus = (UserStatus)Enum.Parse(typeof(UserStatus), context.Attribute(part.PartDefinition.Name, "EmailStatus"));
@@ -64,6 +64,11 @@ namespace Orchard.Widgets.Drivers {
}
protected override void Importing(LayerPart part, ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var name = context.Attribute(part.PartDefinition.Name, "Name");
if (name != null) {
part.Name = name;
@@ -75,6 +75,11 @@ namespace Orchard.Widgets.Drivers {
}
protected override void Importing(WidgetPart part, ContentManagement.Handlers.ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
var title = context.Attribute(part.PartDefinition.Name, "Title");
if (title != null) {
part.Title = title;
@@ -23,6 +23,7 @@ using Orchard.UI.Notify;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;
using Orchard.Workflows.ViewModels;
using Orchard.Workflows.Helpers;
namespace Orchard.Workflows.Controllers {
[ValidateInput(false)]
@@ -298,7 +299,7 @@ namespace Orchard.Workflows.Controllers {
dynamic activity = new JObject();
activity.Name = x.Name;
activity.Id = x.Id;
activity.ClientId = x.Name + "_" + x.Id;
activity.ClientId = x.GetClientId();
activity.Left = x.X;
activity.Top = x.Y;
activity.Start = x.Start;
@@ -323,7 +324,7 @@ namespace Orchard.Workflows.Controllers {
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public ActionResult EditPost(int id, string localId, string data) {
public ActionResult EditPost(int id, string localId, string data, bool clearWorkflows) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
@@ -339,7 +340,6 @@ namespace Orchard.Workflows.Controllers {
var activitiesIndex = new Dictionary<string, ActivityRecord>();
workflowDefinitionRecord.ActivityRecords.Clear();
workflowDefinitionRecord.WorkflowRecords.Clear();
foreach (var activity in state.Activities) {
ActivityRecord activityRecord;
@@ -367,9 +367,32 @@ namespace Orchard.Workflows.Controllers {
});
}
if (clearWorkflows) {
workflowDefinitionRecord.WorkflowRecords.Clear();
}
else {
foreach (var workflowRecord in workflowDefinitionRecord.WorkflowRecords) {
// Update any awaiting activity records with the new activity record.
foreach (var awaitingActivityRecord in workflowRecord.AwaitingActivities) {
var clientId = awaitingActivityRecord.ActivityRecord.GetClientId();
if (activitiesIndex.ContainsKey(clientId)) {
awaitingActivityRecord.ActivityRecord = activitiesIndex[clientId];
}
else {
workflowRecord.AwaitingActivities.Remove(awaitingActivityRecord);
}
}
// Remove any workflows with no awaiting activities.
if (!workflowRecord.AwaitingActivities.Any()) {
workflowDefinitionRecord.WorkflowRecords.Remove(workflowRecord);
}
}
}
Services.Notifier.Information(T("Workflow saved successfully"));
return RedirectToAction("Edit", new { id, localId });
// Don't pass the localId to force the activites to refresh and use the deterministic clientId.
return RedirectToAction("Edit", new { id });
}
[HttpPost, ActionName("Edit")]
@@ -38,5 +38,14 @@ namespace Orchard.Workflows.Models {
/// containing this activity.
/// </summary>
public virtual WorkflowDefinitionRecord WorkflowDefinitionRecord { get; set; }
/// <summary>
/// Gets the Id which can be used on the client.
/// </summary>
/// <returns>An unique Id to represent this activity on the client.</returns>
public string GetClientId() {
return Name + "_" + Id;
}
}
}
@@ -7,6 +7,7 @@
Style.Require("WorkflowsAdmin");
Style.Require("WorkflowsActivities");
Style.Require("jQueryUI_Orchard");
Script.Require("jQueryUI_Dialog").AtFoot();
Script.Require("jsPlumb").AtFoot();
Script.Include("orchard-workflows-serialize.js").AtFoot();
Script.Include("orchard-workflows.js").AtFoot();
@@ -74,23 +75,41 @@
@Html.Hidden("data", String.Empty)
@Html.Hidden("confirm-delete-activity", T("Are you sure you want to remove this activity?"))
@Html.Hidden("confirm-delete-instances", T("Are you sure you want to remove running instances of this workflow?"))
@Html.Hidden("confirm-delete-instances", T("You have running instances of this workflow, do you want to stop them?"))
using (Script.Foot()) {
<script type="text/javascript">
//<![CDATA[
$("form").submit(function () {
saveLocal(localId);
var workflow = loadWorkflow(localId);
var data = JSON.stringify(workflow);
$("[name='data']").val(data);
$("form").submit(function (e, submit, clearWorkflows) {
if(submit){
saveLocal(localId);
var workflow = loadWorkflow(localId);
var data = JSON.stringify(workflow);
$("[name='data']").val(data);
var values = [$("<input>", { type: "hidden", name: "clearWorkflows", value: clearWorkflows }), $("<input>", { type: "hidden", name: "submit.Save", value: "Save" })];
$(this).append(values);
return true;
}
e.preventDefault();
$.ajax({
url: stateUrl + "/" + $("#id").val(),
async: false,
success: function(state) {
if(state.isRunning && !confirm($("#confirm-delete-instances").val())) {
e.preventDefault();
if (state.isRunning) {
var dialog = $('<p>' + $("#confirm-delete-instances").val() + '</p>').dialog({
buttons: {
'@T("Yes")': function() { $('form').trigger('submit', [true, true]); },
'@T("No")': function() { $('form').trigger('submit', [true, false]); },
'@T("Cancel")': function() {
dialog.dialog('close');
}
}
});
}
else {
$('form').trigger('submit', [true, false]);
}
}
});
@@ -0,0 +1,33 @@
using System.IO;
using System.Web;
using Orchard.Settings;
namespace Orchard {
/// <summary>
/// A factory class that creates an HttpContext instance and initializes the HttpContext.Current property with that instance.
/// This is useful when rendering views from a background thread, as some Html Helpers access HttpContext.Current directly, thus preventing a NullReferenceException.
/// </summary>
public class BackgroundHttpContextFactory : IBackgroundHttpContextFactory {
public const string IsBackgroundHttpContextKey = "IsBackgroundHttpContext";
private readonly ISiteService _siteService;
public BackgroundHttpContextFactory(ISiteService siteService) {
_siteService = siteService;
}
public HttpContext CreateHttpContext() {
var url = _siteService.GetSiteSettings().BaseUrl;
var httpContext = new HttpContext(new HttpRequest("", url, ""), new HttpResponse(new StringWriter()));
httpContext.Items[IsBackgroundHttpContextKey] = true;
return httpContext;
}
public void InitializeHttpContext() {
if (HttpContext.Current != null)
return;
HttpContext.Current = CreateHttpContext();
}
}
}
@@ -179,8 +179,8 @@ namespace Orchard.DisplayManagement.Descriptors.ShapeTemplateStrategy {
private ControllerContext CreateControllerContext() {
var controller = new StubController();
var httpContext = _workContextAccessor.GetContext().HttpContext;
var requestContext = httpContext.Request.RequestContext;
var httpContext = _workContextAccessor.GetContext().Resolve<HttpContextBase>();
var requestContext = _workContextAccessor.GetContext().Resolve<RequestContext>();
var routeData = requestContext.RouteData;
routeData.DataTokens["IWorkContextAccessor"] = _workContextAccessor;
+13 -7
View File
@@ -1,6 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Orchard.DisplayManagement.Implementation;
using Orchard.DisplayManagement.Shapes;
@@ -8,24 +10,28 @@ namespace Orchard.DisplayManagement {
public class ShapeDisplay : IShapeDisplay {
private readonly IDisplayHelperFactory _displayHelperFactory;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly HttpContextBase _httpContextBase;
private readonly RequestContext _requestContext;
public ShapeDisplay(
IDisplayHelperFactory displayHelperFactory,
IWorkContextAccessor workContextAccessor) {
IDisplayHelperFactory displayHelperFactory,
IWorkContextAccessor workContextAccessor,
HttpContextBase httpContextBase,
RequestContext requestContext) {
_displayHelperFactory = displayHelperFactory;
_workContextAccessor = workContextAccessor;
_httpContextBase = httpContextBase;
_requestContext = requestContext;
}
public string Display(Shape shape) {
return Display((object)shape);
return Display((object) shape);
}
public string Display(object shape) {
var workContext = _workContextAccessor.GetContext();
var httpContext = workContext.HttpContext;
var viewContext = new ViewContext {
HttpContext = httpContext,
RequestContext = httpContext.Request.RequestContext
HttpContext = _httpContextBase,
RequestContext = _requestContext
};
viewContext.RouteData.DataTokens["IWorkContextAccessor"] = _workContextAccessor;
var display = _displayHelperFactory.CreateHelper(viewContext, new ViewDataContainer());
+12 -10
View File
@@ -15,7 +15,7 @@ using IModelBinderProvider = Orchard.Mvc.ModelBinders.IModelBinderProvider;
namespace Orchard.Environment {
public class DefaultOrchardShell : IOrchardShell {
private readonly Func<Owned<IOrchardShellEvents>> _eventsFactory;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumerable<IRouteProvider> _routeProviders;
private readonly IEnumerable<IHttpRouteProvider> _httpRouteProviders;
private readonly IRoutePublisher _routePublisher;
@@ -26,7 +26,7 @@ namespace Orchard.Environment {
private readonly ShellSettings _shellSettings;
public DefaultOrchardShell(
Func<Owned<IOrchardShellEvents>> eventsFactory,
IWorkContextAccessor workContextAccessor,
IEnumerable<IRouteProvider> routeProviders,
IEnumerable<IHttpRouteProvider> httpRouteProviders,
IRoutePublisher routePublisher,
@@ -35,8 +35,7 @@ namespace Orchard.Environment {
ISweepGenerator sweepGenerator,
IEnumerable<IOwinMiddlewareProvider> owinMiddlewareProviders,
ShellSettings shellSettings) {
_eventsFactory = eventsFactory;
_workContextAccessor = workContextAccessor;
_routeProviders = routeProviders;
_httpRouteProviders = httpRouteProviders;
_routePublisher = routePublisher;
@@ -74,8 +73,10 @@ namespace Orchard.Environment {
_routePublisher.Publish(allRoutes, pipeline);
_modelBinderPublisher.Publish(_modelBinderProviders.SelectMany(provider => provider.GetModelBinders()));
using (var events = _eventsFactory()) {
events.Value.Activated();
using (var scope = _workContextAccessor.CreateWorkContextScope()) {
using (var events = scope.Resolve<Owned<IOrchardShellEvents>>()) {
events.Value.Activated();
}
}
_sweepGenerator.Activate();
@@ -83,10 +84,11 @@ namespace Orchard.Environment {
public void Terminate() {
SafelyTerminate(() => {
using (var events = _eventsFactory()) {
var localEvents = events;
SafelyTerminate(() => localEvents.Value.Terminating());
}
using (var scope = _workContextAccessor.CreateWorkContextScope()) {
using (var events = scope.Resolve<Owned<IOrchardShellEvents>>()) {
SafelyTerminate(() => events.Value.Terminating());
}
}
});
SafelyTerminate(() => _sweepGenerator.Terminate());
+1 -1
View File
@@ -63,7 +63,7 @@ namespace Orchard.Environment {
builder.RegisterType<AppDomainAssemblyNameResolver>().As<IAssemblyNameResolver>().SingleInstance();
builder.RegisterType<GacAssemblyNameResolver>().As<IAssemblyNameResolver>().SingleInstance();
builder.RegisterType<OrchardFrameworkAssemblyNameResolver>().As<IAssemblyNameResolver>().SingleInstance();
builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().InstancePerDependency();
builder.RegisterType<ViewsBackgroundCompilation>().As<IViewsBackgroundCompilation>().SingleInstance();
builder.RegisterType<DefaultExceptionPolicy>().As<IExceptionPolicy>().SingleInstance();
builder.RegisterType<DefaultCriticalErrorProvider>().As<ICriticalErrorProvider>().SingleInstance();
+1 -10
View File
@@ -60,14 +60,11 @@ namespace Orchard.Environment {
return CreateWorkContextScope(httpContext);
var workLifetime = _lifetimeScope.BeginLifetimeScope("work");
httpContext = _httpContextAccessor.CreateContext(workLifetime);
workLifetime.Resolve<WorkContextProperty<HttpContextBase>>().Value = httpContext;
var events = workLifetime.Resolve<IEnumerable<IWorkContextEvents>>();
events.Invoke(e => e.Started(), NullLogger.Instance);
return new ThreadStaticScopeImplementation(
httpContext,
events,
workLifetime,
EnsureThreadStaticContexts(),
@@ -116,9 +113,8 @@ namespace Orchard.Environment {
readonly WorkContext _workContext;
readonly Action _disposer;
public ThreadStaticScopeImplementation(HttpContextBase httpContext, IEnumerable<IWorkContextEvents> events, ILifetimeScope lifetimeScope, ConcurrentDictionary<object, WorkContext> contexts, object workContextKey) {
public ThreadStaticScopeImplementation(IEnumerable<IWorkContextEvents> events, ILifetimeScope lifetimeScope, ConcurrentDictionary<object, WorkContext> contexts, object workContextKey) {
_workContext = lifetimeScope.Resolve<WorkContext>();
httpContext.Items[workContextKey] = _workContext;
contexts.AddOrUpdate(workContextKey, _workContext, (a, b) => _workContext);
_disposer = () => {
@@ -127,11 +123,6 @@ namespace Orchard.Environment {
WorkContext removedContext;
contexts.TryRemove(workContextKey, out removedContext);
lifetimeScope.Dispose();
var staticHttpContext = httpContext as IDisposable;
if(staticHttpContext != null)
staticHttpContext.Dispose();
};
}
@@ -6,7 +6,6 @@ using System.Web;
using Autofac;
using Autofac.Builder;
using Autofac.Core;
using Autofac.Features.Metadata;
using Module = Autofac.Module;
namespace Orchard.Environment {
@@ -24,10 +23,6 @@ namespace Orchard.Environment {
.As<WorkContextProperty<HttpContextBase>>()
.InstancePerMatchingLifetimeScope("work");
builder.Register(ctx => ctx.Resolve<WorkContextProperty<HttpContextBase>>().Value)
.As<HttpContextBase>()
.InstancePerDependency();
builder.RegisterGeneric(typeof(WorkValues<>))
.InstancePerMatchingLifetimeScope("work");
@@ -0,0 +1,8 @@
using System.Web;
namespace Orchard {
public interface IBackgroundHttpContextFactory : IDependency {
HttpContext CreateHttpContext();
void InitializeHttpContext();
}
}
@@ -1,15 +0,0 @@
using System;
namespace Orchard {
/// <summary>
/// A factory class that creates an <see cref="StaticHttpContextScope"/> instance and initializes the HttpContext.Current property with that instance until the scope is disposed of.
/// This is useful when rendering views from a background thread, as some Html Helpers access HttpContext.Current directly, thus preventing a NullReferenceException.
/// </summary>
public interface IStaticHttpContextScopeFactory : IDependency {
/// <summary>
/// Creates a disposable static HttpContext scope. This is safe to use even if there is an actual HttpContext.Current instance.
/// </summary>
/// <returns></returns>
IDisposable CreateStaticScope();
}
}
@@ -0,0 +1,9 @@
using System.Web;
namespace Orchard.Mvc.Extensions {
public static class HttpContextBaseExtensions {
public static bool IsBackgroundContext(this HttpContextBase httpContextBase) {
return httpContextBase == null || httpContextBase is MvcModule.HttpContextPlaceholder;
}
}
}
@@ -1,13 +0,0 @@
using System.Web;
namespace Orchard.Mvc.Extensions {
public static class HttpContextExtensions {
public static bool IsBackgroundContext(this HttpContextBase httpContext) {
return httpContext == null || httpContext is MvcModule.HttpContextPlaceholder;
}
public static bool IsBackgroundContext(this HttpContext httpContext) {
return httpContext == null || httpContext.Items.Contains(StaticHttpContextScopeFactory.IsBackgroundHttpContextKey);
}
}
}
+22 -23
View File
@@ -1,40 +1,39 @@
using System;
using System.Collections.Concurrent;
using System.Web;
using Autofac;
using Orchard.Mvc.Extensions;
namespace Orchard.Mvc {
public class HttpContextAccessor : IHttpContextAccessor {
readonly object _contextKey = new object();
[ThreadStatic]
static ConcurrentDictionary<object, HttpContextBase> _threadStaticContexts;
private HttpContextBase _httpContext;
public HttpContextBase Current() {
if (!HttpContext.Current.IsBackgroundContext())
return new HttpContextWrapper(HttpContext.Current);
return GetContext();
var httpContext = GetStaticProperty();
return !IsBackgroundHttpContext(httpContext) ? new HttpContextWrapper(httpContext) : _httpContext;
}
public HttpContextBase CreateContext(ILifetimeScope lifetimeScope) {
return new MvcModule.HttpContextPlaceholder(
_threadStaticContexts,
_contextKey,
() => "http://localhost" // Use a valid URL always for the fake request. The value itself doesn't matter.
);
public void Set(HttpContextBase httpContext) {
_httpContext = httpContext;
}
private HttpContextBase GetContext() {
HttpContextBase context;
return ThreadStaticContexts.TryGetValue(_contextKey, out context) ? context : null;
private static bool IsBackgroundHttpContext(HttpContext httpContext) {
return httpContext == null || httpContext.Items.Contains(BackgroundHttpContextFactory.IsBackgroundHttpContextKey);
}
static ConcurrentDictionary<object, HttpContextBase> ThreadStaticContexts {
get {
return _threadStaticContexts ?? (_threadStaticContexts = new ConcurrentDictionary<object, HttpContextBase>());
private static HttpContext GetStaticProperty() {
var httpContext = HttpContext.Current;
if (httpContext == null) {
return null;
}
try {
// The "Request" property throws at application startup on IIS integrated pipeline mode.
if (httpContext.Request == null) {
return null;
}
}
catch (Exception) {
return null;
}
return httpContext;
}
}
}
+1 -2
View File
@@ -1,9 +1,8 @@
using System.Web;
using Autofac;
namespace Orchard.Mvc {
public interface IHttpContextAccessor {
HttpContextBase Current();
HttpContextBase CreateContext(ILifetimeScope lifetimeScope);
void Set(HttpContextBase httpContext);
}
}
+7 -43
View File
@@ -1,6 +1,5 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
@@ -10,7 +9,6 @@ using System.Web.Instrumentation;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Orchard.Mvc.Extensions;
using Orchard.Mvc.Routes;
using Orchard.Settings;
@@ -52,21 +50,15 @@ namespace Orchard.Mvc {
// which requires activating the Site content item, which in turn requires a UrlHelper, which in turn requires a RequestContext,
// thus preventing a StackOverflowException.
var baseUrl = new Func<string>(() => siteService.GetSiteSettings().BaseUrl);
var httpContextBase = context.Resolve<IHttpContextAccessor>().Current();
var httpContextBase = new HttpContextPlaceholder(baseUrl);
if (httpContextBase == null) {
context.Resolve<IWorkContextAccessor>().CreateWorkContextScope();
return context.Resolve<IHttpContextAccessor>().Current();
}
context.Resolve<IWorkContextAccessor>().CreateWorkContextScope(httpContextBase);
return httpContextBase;
}
static RequestContext RequestContextFactory(IComponentContext context) {
var httpContextAccessor = context.Resolve<IHttpContextAccessor>();
var httpContext = httpContextAccessor.Current();
if (!httpContext.IsBackgroundContext()) {
if (httpContext != null) {
var mvcHandler = httpContext.Handler as MvcHandler;
if (mvcHandler != null) {
@@ -93,23 +85,16 @@ namespace Orchard.Mvc {
/// <summary>
/// Standin context for background tasks.
/// </summary>
public class HttpContextPlaceholder : HttpContextBase, IDisposable {
public class HttpContextPlaceholder : HttpContextBase {
private readonly Lazy<string> _baseUrl;
private readonly IDictionary _items = new Dictionary<object, object>();
readonly Action _disposer;
public HttpContextPlaceholder(ConcurrentDictionary<object, HttpContextBase> contexts, object contextKey, Func<string> baseUrl) {
public HttpContextPlaceholder(Func<string> baseUrl) {
_baseUrl = new Lazy<string>(baseUrl);
contexts.AddOrUpdate(contextKey, this, (a, b) => this);
_disposer = () => {
HttpContextBase removedContext;
contexts.TryRemove(contextKey, out removedContext);
};
}
public override HttpRequestBase Request {
get { return new HttpRequestPlaceholder(this, new Uri(_baseUrl.Value)); }
get { return new HttpRequestPlaceholder(new Uri(_baseUrl.Value)); }
}
public override IHttpHandler Handler { get; set; }
@@ -118,10 +103,6 @@ namespace Orchard.Mvc {
get { return new HttpResponsePlaceholder(); }
}
public override HttpSessionStateBase Session {
get { return null; }
}
public override IDictionary Items {
get { return _items; }
}
@@ -141,10 +122,6 @@ namespace Orchard.Mvc {
public override object GetService(Type serviceType) {
return null;
}
public void Dispose() {
_disposer();
}
}
public class HttpResponsePlaceholder : HttpResponseBase {
@@ -163,12 +140,9 @@ namespace Orchard.Mvc {
/// standin context for background tasks.
/// </summary>
public class HttpRequestPlaceholder : HttpRequestBase {
private readonly HttpContextBase _httpContext;
private readonly Uri _uri;
private RequestContext _requestContext;
public HttpRequestPlaceholder(HttpContextBase httpContext, Uri uri) {
_httpContext = httpContext;
public HttpRequestPlaceholder(Uri uri) {
_uri = uri;
}
@@ -227,7 +201,7 @@ namespace Orchard.Mvc {
return new NameValueCollection {
{ "SERVER_PORT", _uri.Port.ToString(CultureInfo.InvariantCulture) },
{ "HTTP_HOST", _uri.Authority.ToString(CultureInfo.InvariantCulture) },
};
}
}
@@ -269,16 +243,6 @@ namespace Orchard.Mvc {
return new HttpBrowserCapabilitiesPlaceholder();
}
}
public override RequestContext RequestContext {
get {
if (_requestContext == null) {
_requestContext = new RequestContext(_httpContext, new RouteData());
}
return _requestContext;
}
set { _requestContext = value; }
}
}
public class HttpBrowserCapabilitiesPlaceholder : HttpBrowserCapabilitiesBase {
+4 -4
View File
@@ -56,6 +56,7 @@
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
<NoWarn>0436</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="Autofac, Version=2.1.13.813, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
@@ -149,10 +150,12 @@
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="BackgroundHttpContextFactory.cs" />
<Compile Include="Data\Migration\Schema\AddUniqueConstraintCommand.cs" />
<Compile Include="Data\Migration\Schema\DropUniqueConstraintCommand.cs" />
<Compile Include="Environment\Extensions\Models\LifecycleStatus.cs" />
<Compile Include="Environment\ShellBuilders\ICompositionStrategy.cs" />
<Compile Include="IBackgroundHttpContextFactory.cs" />
<Compile Include="Mvc\Updater.cs" />
<Compile Include="Recipes\Models\ConfigurationContext.cs" />
<Compile Include="Recipes\Models\RecipeBuilderStepConfigurationContext.cs" />
@@ -188,8 +191,6 @@
<Compile Include="Security\NullMembershipService.cs" />
<Compile Include="Security\Providers\DefaultSslSettingsProvider.cs" />
<Compile Include="Security\Providers\DefaultMembershipValidationService.cs" />
<Compile Include="StaticHttpContextScope.cs" />
<Compile Include="StaticHttpContextScopeFactory.cs" />
<Compile Include="Caching\DefaultCacheContextAccessor.cs" />
<Compile Include="Caching\DefaultParallelCacheContext.cs" />
<Compile Include="Caching\ICacheContextAccessor.cs" />
@@ -360,7 +361,7 @@
<Compile Include="Mvc\DataAnnotations\LocalizedModelValidatorProvider.cs" />
<Compile Include="Mvc\DataAnnotations\LocalizedRequiredAttribute.cs" />
<Compile Include="Mvc\Extensions\RouteExtension.cs" />
<Compile Include="Mvc\Extensions\HttpContextExtensions.cs" />
<Compile Include="Mvc\Extensions\HttpContextBaseExtensions.cs" />
<Compile Include="Mvc\FormValueRequiredAttribute.cs" />
<Compile Include="Mvc\HttpContextAccessor.cs" />
<Compile Include="Mvc\HttpContextWorkContext.cs" />
@@ -694,7 +695,6 @@
<Compile Include="WebApi\Filters\OrchardApiActionFilterDispatcher.cs" />
<Compile Include="WebApi\Routes\IHttpRouteProvider.cs" />
<Compile Include="WebApi\Routes\StandardExtensionHttpRouteProvider.cs" />
<Compile Include="IStaticHttpContextScopeFactory.cs" />
<Compile Include="WorkContextExtensions.cs" />
<Compile Include="Mvc\ViewEngines\Razor\RazorCompilationEventsShim.cs" />
<Compile Include="Mvc\ViewEngines\Razor\RazorViewEngineProvider.cs" />
-17
View File
@@ -1,17 +0,0 @@
using System;
using System.Web;
namespace Orchard {
public class StaticHttpContextScope : IDisposable {
private readonly HttpContext _previousHttpContext;
public StaticHttpContextScope(HttpContext stub) {
_previousHttpContext = HttpContext.Current;
HttpContext.Current = stub;
}
public void Dispose() {
HttpContext.Current = _previousHttpContext;
}
}
}
@@ -1,31 +0,0 @@
using System;
using System.IO;
using System.Web;
using Orchard.Settings;
namespace Orchard {
public class StaticHttpContextScopeFactory : IStaticHttpContextScopeFactory {
private readonly Func<ISiteService> _siteService;
public StaticHttpContextScopeFactory(Func<ISiteService> siteService) {
_siteService = siteService;
}
public const string IsBackgroundHttpContextKey = "IsBackgroundHttpContext";
public IDisposable CreateStaticScope() {
// If there already is a current HttpContext, use that one as the stub.
if(HttpContext.Current != null)
return new StaticHttpContextScope(HttpContext.Current);
// We're in a background task (or some other static context like the console),
// so create a stub context so that Html Helpers can still be executed when rendering shapes in background tasks
// (sadly enought some Html Helpers access HttpContext.Current directly).
var url = _siteService().GetSiteSettings().BaseUrl;
var stub = new HttpContext(new HttpRequest("", url, ""), new HttpResponse(new StringWriter()));
stub.Items[IsBackgroundHttpContextKey] = true;
return new StaticHttpContextScope(stub);
}
}
}
+2 -1
View File
@@ -18,7 +18,8 @@ namespace Orchard.Tasks {
public BackgroundService(
IEnumerable<IBackgroundTask> tasks,
ITransactionManager transactionManager,
ShellSettings shellSettings) {
ShellSettings shellSettings,
IBackgroundHttpContextFactory backgroundHttpContextFactory) {
_tasks = tasks;
_transactionManager = transactionManager;
+2 -2
View File
@@ -41,7 +41,7 @@ namespace Orchard.Tasks {
}
void Elapsed(object sender, ElapsedEventArgs e) {
// Current implementation disallows re-entrancy.
// current implementation disallows re-entrancy
if (!System.Threading.Monitor.TryEnter(_timer))
return;
@@ -60,7 +60,7 @@ namespace Orchard.Tasks {
public void DoWork() {
using (var scope = _workContextAccessor.CreateWorkContextScope()) {
// Resolve the manager and invoke it.
// resolve the manager and invoke it
var manager = scope.Resolve<IBackgroundService>();
manager.Sweep();
}
+1
View File
@@ -1,4 +1,5 @@
{
"private": true,
"devDependencies": {
"glob": "^5.0.14",
"path-posix": "^1.0.0",