Compare commits

...

45 Commits

Author SHA1 Message Date
mikkelhm 4377d9294e Bump version to 7.6-beta 2017-03-17 11:51:07 +01:00
Sebastiaan Janssen e3bc6f148a New installer background image 2017-03-17 11:35:15 +01:00
Warren Buckley a43bd13e6a Merge pull request #1798 from umbraco/temp-U4-9621
Fixes: U4-9621 More UI color tweaks
2017-03-16 15:31:30 +00:00
Mads Rasmussen 30d5bfa7b4 move nonode css to less file, update grunt build + update no node colors + font 2017-03-16 15:49:59 +01:00
Stephan 9b8db111dd Merge pull request #1790 from umbraco/temp-U4-9611
U4-9611 Create Property Value Converters for all new UDI Property Edi…
2017-03-16 14:36:17 +01:00
Stephan 7b506fadc6 U4-9611 - minor fix 2017-03-16 14:35:54 +01:00
Claus 1ce44565a3 Merge pull request #1764 from umbraco/temp-u4-9462
U4-9462 units of work cleanup
2017-03-16 13:12:32 +01:00
Stephan e70e651901 U4-9462 - minor fix 2017-03-16 13:10:53 +01:00
Mads Rasmussen 00b0515fc1 Revert "less bright and "dangerous" alerts, notifications and validation messages"
This reverts commit 691c13d1e1.
2017-03-16 10:31:48 +01:00
Morten Christensen d8c04b1f67 Merge pull request #1799 from umbraco/temp-U4-9632
U4-9632 Ensure GUID generation on updated entity types in v7.6 is unique
2017-03-16 10:09:31 +01:00
Shannon 172ef8c379 U4-7093 If allowManuallyChangingPassword=false on new install, installation doesn't work 2017-03-16 18:59:06 +11:00
Claus 7e1f045c09 U4-9632 Ensure GUID generation on updated entity types in v7.6 is unique
removing unused using statements from other migrations.
2017-03-16 08:19:03 +01:00
Sebastiaan Janssen d2fdf7b647 Check if MediaPicker is configured as single or multiple and give back appropriate result for each (IPublishedContent vs IEnumerable<IPublishedContent>) 2017-03-15 23:22:53 +01:00
Sebastiaan Janssen e1942d96d0 Incorporate Stephane's feedback: if we already know we're getting list of int or udi, we don't need to cast, or even test for the PropertyEditorAlias 2017-03-15 23:22:53 +01:00
Stephan 496e6c1711 U4-9462 - missed one safeXml.AcceptChanges 2017-03-15 14:50:42 +01:00
Mads Rasmussen c9fc0fbed1 Update installer gray buttons to purple buttons + align label with input 2017-03-15 14:35:11 +01:00
Stephan 3121ea6111 Merge branch 'dev-v7.6' into temp-u4-9462 2017-03-15 13:48:27 +01:00
Stephan 59ecc6e109 Merge branch 'dev-v7.6' into temp-U4-9611 2017-03-15 13:00:07 +01:00
Stephan eb42b9a4b6 Merge pull request #1796 from umbraco/temp-U4-6566
U4-6566 Membership provider `useLegacyEncoding` should default to `false`
2017-03-15 12:37:09 +01:00
Stephan 82660cf6af Merge branch 'dev-v7.6' into temp-U4-9611 2017-03-15 12:10:27 +01:00
Stephan 54afd3d954 Fix failing test 2017-03-15 12:08:52 +01:00
Mads Rasmussen 9ee3471153 add font smoothing to installer 2017-03-15 10:38:42 +01:00
Mads Rasmussen 691c13d1e1 less bright and "dangerous" alerts, notifications and validation messages 2017-03-15 10:26:05 +01:00
Sebastiaan Janssen 241ccf00a5 U4-6566 Membership provider useLegacyEncoding should default to false 2017-03-14 17:05:24 +01:00
Sebastiaan Janssen 1a0046df95 Merge pull request #1795 from umbraco/temp-U4-9498
U4-9498 LocalLinks as UDI
2017-03-14 15:54:03 +01:00
Sebastiaan Janssen a2ca753dd9 Use RelatedLink class instead of weird extra inline class, convert UDI values 2017-03-14 10:26:13 +01:00
Sebastiaan Janssen 6f516a15aa Boyscout cleanup 2017-03-14 10:25:10 +01:00
Sebastiaan Janssen 223ed41c53 Use the extension method to get published content item - consistent with other PVCs 2017-03-14 10:24:31 +01:00
Sebastiaan Janssen d2a3932626 Merge branch 'dev-v7.6' into temp-U4-9611 2017-03-14 10:22:39 +01:00
Shannon 0a3220df85 Fixes null check, adds another test case 2017-03-14 16:26:17 +11:00
Shannon 9a57f463ce Updates LocalLinks to be UDI, this will support both INT and UDI as LocalLink but when a new LocalLink is picked, it will use the UDI so eventually the INT will be gone 2017-03-14 15:31:30 +11:00
Mads Rasmussen fdfae0f78a increase font size for template insert description 2017-03-13 22:43:24 +01:00
Mads Rasmussen 9ebe7f683a increase font size for validation label 2017-03-13 22:40:12 +01:00
Mads Rasmussen 185af08e75 increase header description font-size 2017-03-13 21:02:43 +01:00
Mads Rasmussen 874c679bfe update tree header 2017-03-13 20:53:55 +01:00
Mads Rasmussen 76a6449ffa increase font size on actions menu 2017-03-13 20:47:36 +01:00
Mads Rasmussen fd8e200bd7 make property editor placeholder lighter + increase font size 2017-03-13 20:38:02 +01:00
Mads Rasmussen aa7e739b0e increase sections label font size 2017-03-13 20:09:44 +01:00
Mads Rasmussen 97f379ff44 add more contrast to placeholder text 2017-03-13 20:06:57 +01:00
Sebastiaan Janssen 3904f9c503 Centralized getting an IPublishedContent item from a Udi in a single extension method so that we're not repeating that code all over the place all the time 2017-03-13 15:49:15 +01:00
Sebastiaan Janssen 89c84676dd U4-9611 Create Property Value Converters for all new UDI Property Editors 2017-03-11 16:44:57 +01:00
Stephan 6439e2fdd0 Merge dev-v7.6 into temp-u4-9462 2017-03-09 15:29:26 +01:00
Stephan 4d24e7bef8 U4-9462 - more units of work cleanup 2017-02-21 13:19:58 +01:00
Stephan 8d5f7af780 U4-9462 - cleanup file unit of work 2017-02-21 13:19:58 +01:00
Stephan 08c8b84a10 U4-9462 - cleanup units of work, code, fixmes 2017-02-21 13:19:58 +01:00
116 changed files with 2432 additions and 1829 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
# Usage: on line 2 put the release version, on line 3 put the version comment (example: beta)
7.6.0
alpha074
beta
+1 -1
View File
@@ -12,4 +12,4 @@ using System.Resources;
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("7.6.0")]
[assembly: AssemblyInformationalVersion("7.6.0-alpha074")]
[assembly: AssemblyInformationalVersion("7.6.0-beta")]
+3 -3
View File
@@ -1,8 +1,6 @@
using System;
using System.Configuration;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.ObjectResolution;
@@ -163,7 +161,9 @@ namespace Umbraco.Core
/// </summary>
public static ApplicationContext Current { get; internal set; }
// fixme
/// <summary>
/// Gets the scope provider.
/// </summary>
internal IScopeProvider ScopeProvider { get { return _databaseContext == null ? null : _databaseContext.ScopeProvider; } }
/// <summary>
@@ -22,12 +22,12 @@ namespace Umbraco.Core.Cache
{
private static readonly TEntity[] EmptyEntities = new TEntity[0]; // const
private readonly RepositoryCachePolicyOptions _options;
public DefaultRepositoryCachePolicy(IRuntimeCacheProvider cache, RepositoryCachePolicyOptions options)
: base(cache)
{
{
if (options == null) throw new ArgumentNullException("options");
_options = options;
_options = options;
}
public override IRepositoryCachePolicy<TEntity, TId> Scoped(IRuntimeCacheProvider runtimeCache, IScope scope)
@@ -244,9 +244,7 @@ namespace Umbraco.Core.Cache
/// <inheritdoc />
public override void ClearAll()
{
// fixme the cache should NOT contain anything else so we can clean all, can't we?
Cache.ClearAllCache();
//Cache.ClearCacheByKeySearch(GetEntityTypeCacheKey());
}
}
}
@@ -18,10 +18,17 @@ namespace Umbraco.Core.Cache
// it is not *that* complicated but then RepositoryBase needs to have a TRepository generic
// type parameter and it all becomes convoluted - keeping it simple for the time being.
// fixme explain
/// <summary>
/// Creates a scoped version of this cache policy.
/// </summary>
/// <param name="runtimeCache">The global isolated runtime cache for this policy.</param>
/// <param name="scope">The scope.</param>
/// <remarks>When a policy is scoped, it means that it has been created with a scoped
/// isolated runtime cache, and now it needs to be wrapped into something that can apply
/// changes to the global isolated runtime cache.</remarks>
IRepositoryCachePolicy<TEntity, TId> Scoped(IRuntimeCacheProvider runtimeCache, IScope scope);
/// <summary>
/// <summary>
/// Gets an entity from the cache, else from the repository.
/// </summary>
/// <param name="id">The identifier.</param>
@@ -24,7 +24,7 @@ namespace Umbraco.Core.Configuration
/// Gets the version comment (like beta or RC).
/// </summary>
/// <value>The version comment.</value>
public static string CurrentComment { get { return "alpha074"; } }
public static string CurrentComment { get { return "beta"; } }
// Get the version of the umbraco.dll by looking at a class in that dll
// Had to do it like this due to medium trust issues, see: http://haacked.com/archive/2010/11/04/assembly-location-and-medium-trust.aspx
+10
View File
@@ -89,6 +89,11 @@ namespace Umbraco.Core
/// </summary>
public const string Media = "B796F64C-1F99-4FFB-B886-4BF4BC011A9C";
/// <summary>
/// Guid for a Document object.
/// </summary>
public static readonly Guid MediaGuid = new Guid(Media);
/// <summary>
/// Guid for the Media Recycle Bin.
/// </summary>
@@ -148,6 +153,11 @@ namespace Umbraco.Core
/// </summary>
public const string Template = "6FBDE604-4178-42CE-A10B-8A2600A2F07D";
/// <summary>
/// Guid for a Template object.
/// </summary>
public static readonly Guid TemplateTypeGuid = new Guid(Template);
/// <summary>
/// Guid for a Lock object.
/// </summary>
-1
View File
@@ -173,7 +173,6 @@ namespace Umbraco.Core
return new ServiceContext(
new RepositoryFactory(ApplicationCache, ProfilingLogger.Logger, dbContext.SqlSyntax, UmbracoConfig.For.UmbracoSettings()),
new PetaPocoUnitOfWorkProvider(scopeProvider),
new FileUnitOfWorkProvider(scopeProvider),
ApplicationCache,
ProfilingLogger.Logger,
msgFactory);
+5 -35
View File
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlServerCe;
using System.IO;
@@ -34,7 +33,7 @@ namespace Umbraco.Core
private string _connectionString;
private string _providerName;
private DatabaseSchemaResult _result;
private DateTime? _connectionLastChecked = null;
private DateTime? _connectionLastChecked;
/// <summary>
/// The number of minutes to throttle the checks to CanConnect
@@ -99,10 +98,10 @@ namespace Umbraco.Core
SqlSyntaxContext.SqlSyntaxProvider = SqlSyntax;
var asDbFactory2 = factory as IDatabaseFactory2;
ScopeProvider = asDbFactory2 == null
? new ScopeProvider(new DatabaseFactoryWrapper(factory))
ScopeProvider = asDbFactory2 == null
? new ScopeProvider(new DatabaseFactoryWrapper(factory))
: new ScopeProvider(asDbFactory2);
_logger = logger;
_configured = true;
}
@@ -197,42 +196,13 @@ namespace Umbraco.Core
{
throw new InvalidOperationException("Cannot create a database instance, there is no available connection string");
}
return ScopeProvider.GetAmbientOrNoScope().Database;
//var scope = ScopeProvider.AmbientScope;
//return scope != null ? scope.Database : ScopeProvider.CreateNoScope().Database;
}
}
/// <summary>
/// Replaces the "ambient" database (if any) and by a new temp database.
/// </summary>
/// <remarks>
/// <para>The returned IDisposable *must* be diposed in order to properly dispose the temp database and
/// restore the original "ambient" database (if any).</para>
/// <para>This is to be used in background tasks to ensure that they have an "ambient" database which
/// will be properly removed from call context and does not interfere with anything else. In most case
/// it is not replacing anything, just temporarily installing a database in context.</para>
/// </remarks>
// fixme - this should just entirely be replaced by Scope?
/*
public virtual IDisposable UseSafeDatabase(bool force = false)
{
var factory = _factory as DefaultDatabaseFactory;
if (factory == null) throw new NotSupportedException();
if (DefaultDatabaseFactory.HasAmbientDatabase)
{
return force
? new UsingDatabase(DefaultDatabaseFactory.DetachAmbientDatabase(), factory.CreateDatabase())
: new UsingDatabase(null, null);
}
// create a new, temp, database (will be disposed with UsingDatabase)
return new UsingDatabase(null, factory.CreateDatabase());
}
*/
/// <summary>
/// Boolean indicating whether the database has been configured
/// </summary>
@@ -16,13 +16,17 @@ namespace Umbraco.Core.Events
protected override void ScopeExitCompleted()
{
// fixme - we'd need to de-duplicate events somehow, etc - and the deduplication should be last in wins
// processing only the last instance of each event...
// this is probably far from perfect, because if eg a content is saved in a list
// and then as a single content, the two events will probably not be de-duplicated,
// but it's better than nothing
foreach (var e in GetEvents(EventDefinitionFilter.All))
foreach (var e in GetEvents(EventDefinitionFilter.LastIn))
{
e.RaiseEvent();
// fixme - not sure I like doing it here - but then where? how?
// separating concerns means that this should probably not be here,
// but then where should it be (without making things too complicated)?
var delete = e.Args as IDeletingMediaFilesEventArgs;
if (delete != null && delete.MediaFilesToDelete.Count > 0)
MediaFileSystem.DeleteMediaFiles(delete.MediaFilesToDelete);
@@ -35,13 +39,7 @@ namespace Umbraco.Core.Events
{
get
{
if (_mediaFileSystem != null) return _mediaFileSystem;
// fixme - insane! reading config goes cross AppDomain and serializes context?
using (new SafeCallContext())
{
return _mediaFileSystem = FileSystemProviderManager.Current.MediaFileSystem;
}
return _mediaFileSystem ?? (_mediaFileSystem = FileSystemProviderManager.Current.MediaFileSystem);
}
}
}
@@ -45,7 +45,8 @@ namespace Umbraco.Core.IO
private IScopeProviderInternal ScopeProvider
{
// fixme - 'course this is bad, but enough for now
// this is bad, but enough for now, and we'll refactor
// in v8 when we'll get rid of this class' singleton
// beware: means that we capture the "current" scope provider - take care in tests!
get { return ApplicationContext.Current == null ? null : ApplicationContext.Current.ScopeProvider as IScopeProviderInternal; }
}
+2 -26
View File
@@ -302,7 +302,7 @@ namespace Umbraco.Core.IO
{
var property = GetProperty(content, propertyTypeAlias);
var svalue = property.Value as string;
var oldpath = svalue == null ? null : GetRelativePath(svalue); // FIXME DELETE?
var oldpath = svalue == null ? null : GetRelativePath(svalue);
if (string.IsNullOrWhiteSpace(oldpath) == false && oldpath != filepath)
DeleteFile(oldpath, true);
property.Value = GetUrl(filepath);
@@ -466,27 +466,6 @@ namespace Umbraco.Core.IO
var dir = Path.GetDirectoryName(file);
DeleteDirectory(dir, true);
}
// I don't even understand...
/*
var relativeFilePath = GetRelativePath(file); // fixme - should be relative already
if (FileExists(relativeFilePath) == false) return;
var parentDirectory = Path.GetDirectoryName(relativeFilePath);
// don't want to delete the media folder if not using directories.
if (_contentSection.UploadAllowDirectories && parentDirectory != GetRelativePath("/"))
{
//issue U4-771: if there is a parent directory the recursive parameter should be true
DeleteDirectory(parentDirectory, string.IsNullOrEmpty(parentDirectory) == false);
}
else
{
DeleteFile(file, true);
}
*/
}
catch (Exception e)
{
@@ -549,7 +528,7 @@ namespace Umbraco.Core.IO
PropertyType propertyType)
{
// get the original image from the original stream
if (filestream.CanSeek) filestream.Seek(0, 0); // fixme - what if we cannot seek?
if (filestream.CanSeek) filestream.Seek(0, 0);
using (var image = Image.FromStream(filestream))
{
return GenerateThumbnails(image, filepath, propertyType);
@@ -658,9 +637,6 @@ namespace Umbraco.Core.IO
var rect = new Rectangle(0, 0, width, height);
graphics.DrawImage(originImage, rect, 0, 0, originImage.Width, originImage.Height, GraphicsUnit.Pixel);
// copy metadata
// fixme - er... no?
// get an encoder - based upon the file type
var extension = (Path.GetExtension(resizedFilepath) ?? "").TrimStart('.').ToLowerInvariant();
var encoders = ImageCodecInfo.GetImageEncoders();
+6 -2
View File
@@ -155,7 +155,9 @@ namespace Umbraco.Core.IO
if (directory == null) throw new InvalidOperationException("Could not get directory.");
Directory.CreateDirectory(directory); // ensure it exists
if (stream.CanSeek) // fixme - what else?
// if can seek, be safe and go back to start, else...
// hope that the stream hasn't been read already
if (stream.CanSeek)
stream.Seek(0, 0);
using (var destination = (Stream) File.Create(fullPath))
@@ -286,7 +288,9 @@ namespace Umbraco.Core.IO
var opath = path;
path = EnsureDirectorySeparatorChar(path);
// fixme - this part should go!
// TODO in v8 this should be cleaned up
// the first part should probably removed
// not sure what we are doing here - so if input starts with a (back) slash,
// we assume it's not a FS relative path and we try to convert it... but it
// really makes little sense?
+12 -13
View File
@@ -7,7 +7,6 @@ using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.IO;
using Umbraco.Core.Media;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
@@ -42,7 +41,7 @@ namespace Umbraco.Core.Models
/// * The item exists and is published
/// * A call to ContentService.Save is made
/// * The item has not been modified whatsoever apart from changing it's published status from published to saved
///
///
/// In this case, there is no reason to make any database changes at all
/// </remarks>
internal static bool RequiresSaving(this IContent entity)
@@ -62,7 +61,7 @@ namespace Umbraco.Core.Models
/// * The item exists and is published
/// * A call to ContentService.Save is made
/// * The item has not been modified whatsoever apart from changing it's published status from published to saved
///
///
/// In this case, there is no reason to make any database changes at all
/// </remarks>
internal static bool RequiresSaving(this IContent entity, PublishedState publishedState)
@@ -70,7 +69,7 @@ namespace Umbraco.Core.Models
var publishedChanged = entity.IsPropertyDirty("Published") && publishedState != PublishedState.Unpublished;
//check if any user prop has changed
var propertyValueChanged = entity.IsAnyUserPropertyDirty();
//We need to know if any other property apart from Published was changed here
//don't create a new version if the published state has changed to 'Save' but no data has actually been changed
if (publishedChanged && entity.Published == false && propertyValueChanged == false)
@@ -302,9 +301,9 @@ namespace Umbraco.Core.Models
return content.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Contains(recycleBinId.ToInvariantString());
}
/// <summary>
/// Removes characters that are not valide XML characters from all entity properties
/// Removes characters that are not valide XML characters from all entity properties
/// of type string. See: http://stackoverflow.com/a/961504/5018
/// </summary>
/// <returns></returns>
@@ -456,7 +455,7 @@ namespace Umbraco.Core.Models
/// <param name="value">The uploaded <see cref="HttpPostedFileBase"/>.</param>
public static void SetValue(this IContentBase content, string propertyTypeAlias, HttpPostedFileBase value)
{
// ensure we get the filename without the path in IE in intranet mode
// ensure we get the filename without the path in IE in intranet mode
// http://stackoverflow.com/questions/382464/httppostedfile-filename-different-from-ie
var filename = value.FileName;
var pos = filename.LastIndexOf(@"\", StringComparison.InvariantCulture);
@@ -468,10 +467,10 @@ namespace Umbraco.Core.Models
if (pos > 0)
filename = filename.Substring(pos + 1);
// get a safe filename - should this be done by MediaHelper?
// get a safe & clean filename
filename = IOHelper.SafeFileName(filename);
if (string.IsNullOrWhiteSpace(filename)) return;
filename = filename.ToLower(); // fixme - er... why?
filename = filename.ToLower();
FileSystemProviderManager.Current.MediaFileSystem.SetUploadFile(content, propertyTypeAlias, filename, value.InputStream);
}
@@ -513,10 +512,10 @@ namespace Umbraco.Core.Models
{
if (filename == null || filestream == null) return;
// get a safe filename - should this be done by MediaHelper?
// get a safe & clean filename
filename = IOHelper.SafeFileName(filename);
if (string.IsNullOrWhiteSpace(filename)) return;
filename = filename.ToLower(); // fixme - er... why?
filename = filename.ToLower();
FileSystemProviderManager.Current.MediaFileSystem.SetUploadFile(content, propertyTypeAlias, filename, filestream);
}
@@ -548,7 +547,7 @@ namespace Umbraco.Core.Models
#endregion
#region User/Profile methods
/// <summary>
/// Gets the <see cref="IProfile"/> for the Creator of this media item.
/// </summary>
@@ -623,7 +622,7 @@ namespace Umbraco.Core.Models
///// <param name="tagGroup"></param>
///// <returns></returns>
///// <remarks>
///// The tags returned are only relavent for published content & saved media or members
///// The tags returned are only relavent for published content & saved media or members
///// </remarks>
//public static IEnumerable<ITag> GetTags(this IContentBase content, string propertyTypeAlias, string tagGroup = "default")
//{
@@ -1,85 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Services;
namespace Umbraco.Core.Models
{
//fixme: This whole thing needs to go, it's super hacky and doens't need to exist in the first place
internal static class ContentTypeExtensions
{
/// <summary>
/// Get all descendant content types
/// </summary>
/// <param name="contentType"></param>
/// <param name="contentTypeService"></param>
/// <returns></returns>
public static IEnumerable<IContentTypeBase> Descendants(this IContentTypeBase contentType, IContentTypeService contentTypeService)
{
if (contentType is IContentType)
{
var descendants = contentTypeService.GetContentTypeChildren(contentType.Id)
.SelectRecursive(type => contentTypeService.GetContentTypeChildren(type.Id));
return descendants;
}
if (contentType is IMediaType)
{
var descendants = contentTypeService.GetMediaTypeChildren(contentType.Id)
.SelectRecursive(type => contentTypeService.GetMediaTypeChildren(type.Id));
return descendants;
}
//No other content types have children (i.e. member types)
return Enumerable.Empty<IContentTypeBase>();
}
/// <summary>
/// Get all descendant content types
/// </summary>
/// <param name="contentType"></param>
/// <param name="contentTypeService"></param>
/// <returns></returns>
public static IEnumerable<IContentTypeBase> Descendants(this IContentTypeBase contentType, ContentTypeServiceBase contentTypeService)
{
var cService = contentTypeService as IContentTypeService;
return cService == null ? Enumerable.Empty<IContentTypeBase>() : contentType.Descendants(cService);
}
/// <summary>
/// Get all descendant and self content types
/// </summary>
/// <param name="contentType"></param>
/// <param name="contentTypeService"></param>
/// <returns></returns>
public static IEnumerable<IContentTypeBase> DescendantsAndSelf(this IContentTypeBase contentType, IContentTypeService contentTypeService)
{
var descendantsAndSelf = new[] { contentType }.Concat(contentType.Descendants(contentTypeService));
return descendantsAndSelf;
}
/// <summary>
/// Get all descendant and self content types
/// </summary>
/// <param name="contentType"></param>
/// <param name="contentTypeService"></param>
/// <returns></returns>
public static IEnumerable<IContentTypeBase> DescendantsAndSelf(this IContentTypeBase contentType, ContentTypeServiceBase contentTypeService)
{
var descendantsAndSelf = new[] { contentType }.Concat(contentType.Descendants(contentTypeService));
return descendantsAndSelf;
}
///// <summary>
///// Returns the descendant content type Ids for the given content type
///// </summary>
///// <param name="contentType"></param>
///// <returns></returns>
//public static IEnumerable<int> DescendantIds(this IContentTypeBase contentType)
//{
// return ((ContentTypeService) ApplicationContext.Current.Services.ContentTypeService)
// .GetDescendantContentTypeIds(contentType.Id);
//}
}
}
@@ -1,6 +1,5 @@
using System.Linq;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenSixZero
@@ -1,6 +1,5 @@
using System.Linq;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenSixZero
@@ -1,6 +1,5 @@
using System;
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.SqlSyntax;
@@ -44,7 +43,7 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenSixZero
private static string UpdateMacroGuids(Database database)
{
var updates = database.Query<dynamic>("SELECT id, macroAlias FROM cmsMacro")
.Select(macro => Tuple.Create((int) macro.id, ((string) macro.macroAlias).ToGuid()))
.Select(macro => Tuple.Create((int) macro.id, ("macro____" + (string) macro.macroAlias).ToGuid()))
.ToList();
foreach (var update in updates)
@@ -58,7 +57,7 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenSixZero
var updates = database.Query<dynamic>(@"SELECT cmsMacroProperty.id id, macroPropertyAlias propertyAlias, cmsMacro.macroAlias macroAlias
FROM cmsMacroProperty
JOIN cmsMacro ON cmsMacroProperty.macro=cmsMacro.id")
.Select(prop => Tuple.Create((int) prop.id, ((string) prop.macroAlias + "____" + (string) prop.propertyAlias).ToGuid()))
.Select(prop => Tuple.Create((int) prop.id, ("macro____" + (string) prop.macroAlias + "____" + (string) prop.propertyAlias).ToGuid()))
.ToList();
foreach (var update in updates)
@@ -1,6 +1,5 @@
using System;
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.SqlSyntax;
@@ -32,7 +31,7 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenSixZero
private static string UpdateRelationTypeGuids(Database database)
{
var updates = database.Query<dynamic>("SELECT id, alias, name FROM umbracoRelationType")
.Select(relationType => Tuple.Create((int) relationType.id, ((string) relationType.alias + "____" + (string) relationType.name).ToGuid()))
.Select(relationType => Tuple.Create((int) relationType.id, ("relationType____" + (string) relationType.alias + "____" + (string) relationType.name).ToGuid()))
.ToList();
foreach (var update in updates)
@@ -1,5 +1,4 @@
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.SqlSyntax;
@@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.SqlSyntax;
@@ -31,7 +31,7 @@ namespace Umbraco.Core.Persistence.Repositories
/// </summary>
protected internal new IScopeUnitOfWork UnitOfWork
{
get { return (IScopeUnitOfWork)base.UnitOfWork; }
get { return base.UnitOfWork; }
}
protected UmbracoDatabase Database
@@ -75,10 +75,5 @@ namespace Umbraco.Core.Persistence.Repositories
Database.Execute(delete, new { Id = GetEntityId(entity) });
}
}
protected virtual TId GetEntityId(TEntity entity)
{
return (TId)(object)entity.Id;
}
}
}
@@ -13,10 +13,10 @@ namespace Umbraco.Core.Persistence.Repositories
{
internal abstract class RepositoryBase : DisposableObject
{
private readonly IUnitOfWork _work;
private readonly IScopeUnitOfWork _work;
private readonly CacheHelper _globalCache;
protected RepositoryBase(IUnitOfWork work, CacheHelper cache, ILogger logger)
protected RepositoryBase(IScopeUnitOfWork work, CacheHelper cache, ILogger logger)
{
if (work == null) throw new ArgumentNullException("work");
if (cache == null) throw new ArgumentNullException("cache");
@@ -29,7 +29,7 @@ namespace Umbraco.Core.Persistence.Repositories
/// <summary>
/// Returns the Unit of Work added to the repository
/// </summary>
protected internal IUnitOfWork UnitOfWork
protected internal IScopeUnitOfWork UnitOfWork
{
get { return _work; }
}
@@ -76,7 +76,7 @@ namespace Umbraco.Core.Persistence.Repositories
internal abstract class RepositoryBase<TId, TEntity> : RepositoryBase, IRepositoryQueryable<TId, TEntity>, IUnitOfWorkRepository
where TEntity : class, IAggregateRoot
{
protected RepositoryBase(IUnitOfWork work, CacheHelper cache, ILogger logger)
protected RepositoryBase(IScopeUnitOfWork work, CacheHelper cache, ILogger logger)
: base(work, cache, logger)
{
}
@@ -102,7 +102,7 @@ namespace Umbraco.Core.Persistence.Repositories
{
if (_isolatedCache != null) return _isolatedCache;
var scope = ((ScopeUnitOfWork) UnitOfWork).Scope; // fixme cast!
var scope = UnitOfWork.Scope;
IsolatedRuntimeCache provider;
switch (scope.RepositoryCacheMode)
{
@@ -179,14 +179,17 @@ namespace Umbraco.Core.Persistence.Repositories
if (GlobalCache == CacheHelper.NoCache)
return _cachePolicy = NoRepositoryCachePolicy<TEntity, TId>.Instance;
// create the cache policy using IsolatedCache which is either global
// or scoped depending on the repository cache mode for the current scope
_cachePolicy = CreateCachePolicy(IsolatedCache);
var scope = ((ScopeUnitOfWork) UnitOfWork).Scope; // fixme cast!
var scope = UnitOfWork.Scope;
switch (scope.RepositoryCacheMode)
{
case RepositoryCacheMode.Default:
break;
case RepositoryCacheMode.Scoped:
_cachePolicy = _cachePolicy.Scoped(GetIsolatedCache(GlobalCache.IsolatedRuntimeCache), scope);
var globalIsolatedCache = GetIsolatedCache(GlobalCache.IsolatedRuntimeCache);
_cachePolicy = _cachePolicy.Scoped(globalIsolatedCache, scope);
break;
default:
throw new Exception("oops: cache mode.");
@@ -21,7 +21,9 @@ namespace Umbraco.Core.Persistence.Repositories
: base(work, CacheHelper.NoCache, logger, sqlSyntax)
{
// managing the cache our own way (no policy etc)
// fixme - ServerRegistrationRepository does *not* implement scoped cache at the moment!
// note: this means that the ServerRegistrationRepository does *not* implement scoped cache,
// and this is because the repository is special and should not participate in scopes
// (cleanup in v8)
_globalCache = globalCache;
}
@@ -32,7 +32,7 @@ namespace Umbraco.Core.Persistence
//if (sqlSyntax == null) throw new ArgumentNullException("sqlSyntax");
if (settings == null) throw new ArgumentNullException("settings");
_cacheHelper = cacheHelper;
_cacheHelper = cacheHelper;
//IMPORTANT: We will force the DeepCloneRuntimeCacheProvider to be used here which is a wrapper for the underlying
// runtime cache to ensure that anything that can be deep cloned in/out is done so, this also ensures that our tracks
@@ -71,7 +71,7 @@ namespace Umbraco.Core.Persistence
{
}
[Obsolete("Use the ctor specifying all dependencies instead, NOTE: disableAllCache has zero effect")]
[Obsolete("Use the ctor specifying all dependencies instead, NOTE: disableAllCache has zero effect")]
public RepositoryFactory(bool disableAllCache, CacheHelper cacheHelper)
: this(cacheHelper, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
@@ -86,7 +86,7 @@ namespace Umbraco.Core.Persistence
{
}
#endregion
public virtual IExternalLoginRepository CreateExternalLoginRepository(IScopeUnitOfWork uow)
@@ -235,12 +235,13 @@ namespace Umbraco.Core.Persistence
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual IStylesheetRepository CreateStylesheetRepository(IUnitOfWork uow, IDatabaseUnitOfWork db)
{
// note: the second unit of work is ignored.
return new StylesheetRepository(uow, FileSystemProviderManager.Current.StylesheetsFileSystem);
}
public virtual ITemplateRepository CreateTemplateRepository(IScopeUnitOfWork uow)
{
return new TemplateRepository(uow,
return new TemplateRepository(uow,
_cacheHelper,
_logger, _sqlSyntax,
FileSystemProviderManager.Current.MasterPagesFileSystem,
@@ -279,7 +280,7 @@ namespace Umbraco.Core.Persistence
}
public virtual IUserRepository CreateUserRepository(IScopeUnitOfWork uow)
{
{
return new UserRepository(
uow,
//Need to cache users - we look up user information more than anything in the back office!
@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Scoping;
namespace Umbraco.Core.Persistence.UnitOfWork
{
internal class FileUnitOfWork : ScopeUnitOfWork
{
// fixme
// soon as FileUnitOfWork inherits from ScopeUnitOfWork it does not make any sense anymore to keep this class around?!
public FileUnitOfWork(IScopeProvider scopeProvider, IsolationLevel isolationLevel = IsolationLevel.Unspecified)
: base(scopeProvider, isolationLevel)
{ }
}
}
@@ -4,10 +4,15 @@ using Umbraco.Core.Scoping;
namespace Umbraco.Core.Persistence.UnitOfWork
{
// note: the concept of "file unit of work" does not make sense anymore in v7.6
// and we should probably remove this class, which is not used anywhere, but for
// the time being we keep it here - just not to break too many things.
/// <summary>
/// Represents a Unit of Work Provider for creating a file unit of work
/// </summary>
public class FileUnitOfWorkProvider : ScopeUnitOfWorkProvider // fixme - what's the point?
[Obsolete("Use the ScopeUnitOfWorkProvider instead.", false)]
public class FileUnitOfWorkProvider : ScopeUnitOfWorkProvider
{
[Obsolete("Use the ctor specifying a IScopeProvider instead")]
public FileUnitOfWorkProvider()
@@ -18,11 +23,8 @@ namespace Umbraco.Core.Persistence.UnitOfWork
: base(scopeProvider)
{ }
// fixme - returning a IScopeUnitOfWork instead of a IUnitOfWork here is a breaking change!
// this is bad, we're going to end up creating // units of work which is ... really bad
public override IScopeUnitOfWork GetUnitOfWork()
{
// fixme - no point returning a FileUnitOfWork if its equivalent to ScopeUnitOfWork
return new ScopeUnitOfWork(ScopeProvider);
}
}
@@ -18,19 +18,9 @@ namespace Umbraco.Core.Persistence.UnitOfWork
// creates a unit of work
// support specifying an isolation level
// support auto-commit - beware!
// fixme - should we be able to specify ALL scope options?
// fixme - that isolation level thing is a pain because of the above existing method
IScopeUnitOfWork GetUnitOfWork(bool commit);
IScopeUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel, bool commit = false);
// creates a readonly unit of work
// the readonly unit of work will not accept operations, and will auto-complete
// of course it would be a bad idea to use it for anything else than reading
// fixme - implement that one FOR REAL not as an extension method
// the extension method was a ugly hack
// or maybe we want a autocommit flag in the ctor?
//IScopeUnitOfWork GetReadOnlyUnitOfWork();
//IScopeUnitOfWork GetReadOnlyUnitOfWork(bool autocommit = false);
// support auto-commit - but beware! it will be committed, whatever happens
// TODO in v8 this should all be merged as one single method with optional args
IScopeUnitOfWork GetUnitOfWork(bool readOnly);
IScopeUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel, bool readOnly = false);
}
}
@@ -16,6 +16,7 @@ namespace Umbraco.Core.Persistence.UnitOfWork
private readonly IsolationLevel _isolationLevel;
private readonly IScopeProvider _scopeProvider;
private bool _completeScope;
private readonly bool _readOnly;
private IScope _scope;
private Guid _key;
@@ -29,11 +30,11 @@ namespace Umbraco.Core.Persistence.UnitOfWork
/// </summary>
/// <param name="scopeProvider"></param>
/// <param name="isolationLevel"></param>
/// <param name="commit"></param>
/// <param name="readOnly"></param>
/// <remarks>
/// This should normally not be used directly and should be created with the UnitOfWorkProvider
/// </remarks>
internal ScopeUnitOfWork(IScopeProvider scopeProvider, IsolationLevel isolationLevel = IsolationLevel.Unspecified, bool commit = false)
internal ScopeUnitOfWork(IScopeProvider scopeProvider, IsolationLevel isolationLevel = IsolationLevel.Unspecified, bool readOnly = false)
{
_scopeProvider = scopeProvider;
_isolationLevel = isolationLevel;
@@ -43,7 +44,7 @@ namespace Umbraco.Core.Persistence.UnitOfWork
// be false by default
// if set to true... the UnitOfWork is "auto-commit" which means that even in the case of
// an exception, the scope would still be completed - ppl should use it with great care!
_completeScope = commit;
_completeScope = _readOnly = readOnly;
}
/// <summary>
@@ -53,6 +54,9 @@ namespace Umbraco.Core.Persistence.UnitOfWork
/// <param name="repository">The <see cref="IUnitOfWorkRepository" /> participating in the transaction</param>
public void RegisterAdded(IEntity entity, IUnitOfWorkRepository repository)
{
if (_readOnly)
throw new NotSupportedException("This unit of work is read-only.");
_operations.Enqueue(new Operation
{
Entity = entity,
@@ -68,7 +72,10 @@ namespace Umbraco.Core.Persistence.UnitOfWork
/// <param name="repository">The <see cref="IUnitOfWorkRepository" /> participating in the transaction</param>
public void RegisterChanged(IEntity entity, IUnitOfWorkRepository repository)
{
_operations.Enqueue(
if (_readOnly)
throw new NotSupportedException("This unit of work is read-only.");
_operations.Enqueue(
new Operation
{
Entity = entity,
@@ -84,7 +91,10 @@ namespace Umbraco.Core.Persistence.UnitOfWork
/// <param name="repository">The <see cref="IUnitOfWorkRepository" /> participating in the transaction</param>
public void RegisterRemoved(IEntity entity, IUnitOfWorkRepository repository)
{
_operations.Enqueue(
if (_readOnly)
throw new NotSupportedException("This unit of work is read-only.");
_operations.Enqueue(
new Operation
{
Entity = entity,
@@ -116,6 +126,9 @@ namespace Umbraco.Core.Persistence.UnitOfWork
{
// this happens in a scope-managed transaction
if (_readOnly)
throw new NotSupportedException("This unit of work is read-only.");
// in case anything goes wrong
_completeScope = false;
@@ -24,48 +24,28 @@ namespace Umbraco.Core.Persistence.UnitOfWork
return new ScopeUnitOfWork(ScopeProvider);
}
/// <summary>
/// Creates a Unit of work with a new UmbracoDatabase instance for the work item/transaction.
/// </summary>
/// <returns></returns>
/// <remarks>
/// Each PetaPoco UOW uses it's own Database object, not the shared Database object that comes from
/// the ApplicationContext.Current.DatabaseContext.Database. This is because each transaction should use it's own Database
/// and we Dispose of this Database object when the UOW is disposed.
/// fixme NO we dispose of it when the transaction completes
/// fixme just inheritdoc!
/// </remarks>
/// <inheritdoc />
public virtual IScopeUnitOfWork GetUnitOfWork()
{
return new ScopeUnitOfWork(ScopeProvider);
}
/// <summary>
/// Creates a Unit of work with a new UmbracoDatabase instance for the work item/transaction.
/// </summary>
/// <returns></returns>
/// <remarks>
/// Each PetaPoco UOW uses it's own Database object, not the shared Database object that comes from
/// the ApplicationContext.Current.DatabaseContext.Database. This is because each transaction should use it's own Database
/// and we Dispose of this Database object when the UOW is disposed.
/// fixme NO
/// fixme just inheritdoc!
/// </remarks>
/// <inheritdoc />
public IScopeUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel)
{
return new ScopeUnitOfWork(ScopeProvider, isolationLevel);
}
/// <inheritdoc />
public IScopeUnitOfWork GetUnitOfWork(bool commit)
public IScopeUnitOfWork GetUnitOfWork(bool readOnly)
{
return new ScopeUnitOfWork(ScopeProvider, commit: commit);
return new ScopeUnitOfWork(ScopeProvider, readOnly: readOnly);
}
/// <inheritdoc />
public IScopeUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel, bool commit)
public IScopeUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel, bool readOnly)
{
return new ScopeUnitOfWork(ScopeProvider, isolationLevel, commit: commit);
return new ScopeUnitOfWork(ScopeProvider, isolationLevel, readOnly: readOnly);
}
}
}
@@ -80,7 +80,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters
.PreValuesAsDictionary.FirstOrDefault(
x => string.Equals(x.Key, "storageType", StringComparison.InvariantCultureIgnoreCase)).Value;
if (storageType.Value.InvariantEquals("Json"))
if (storageType != null && storageType.Value.InvariantEquals("Json"))
{
return true;
}
@@ -176,6 +176,7 @@ namespace Umbraco.Core.Scoping
}
}
// this is for tests exclusively until we have a proper accessor in v8
internal static Func<IDictionary> HttpContextItemsGetter { get; set; }
private static IDictionary HttpContextItems
@@ -324,6 +324,13 @@ namespace Umbraco.Core.Security
throw new MembershipPasswordException("Change password canceled due to password validation failure.");
}
//Special case to allow changing password without validating existing credentials
//This is used during installation only
if (AllowManuallyChangingPassword == false && ApplicationContext.Current.IsConfigured == false && oldPassword == "default")
{
return PerformChangePassword(username, oldPassword, newPassword);
}
if (AllowManuallyChangingPassword == false)
{
if (ValidateUser(username, oldPassword) == false) return false;
File diff suppressed because it is too large Load Diff
+151 -134
View File
@@ -1,22 +1,15 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;
using AutoMapper;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
@@ -76,6 +69,7 @@ namespace Umbraco.Core.Services
}
catch (Exception ex)
{
uow.Commit();
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
@@ -113,6 +107,7 @@ namespace Umbraco.Core.Services
}
catch (Exception ex)
{
uow.Commit();
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
@@ -139,7 +134,7 @@ namespace Umbraco.Core.Services
TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> savedEvent,
EntityContainer container,
Guid containerObjectType,
string objectTypeName,
string objectTypeName,
string savedEventName,
int userId)
{
@@ -159,10 +154,9 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
// fixme - how does it work w/name?!
if (uow.Events.DispatchCancelable(savingEvent, this, new SaveEventArgs<EntityContainer>(container, evtMsgs)))
//if (savingEvent.IsRaisedEventCancelled(new SaveEventArgs<EntityContainer>(container, evtMsgs), this, UowProvider))
{
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
@@ -189,7 +183,7 @@ namespace Umbraco.Core.Services
private EntityContainer GetContainer(int containerId, Guid containerObjectType)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType);
return repo.Get(containerId);
@@ -198,7 +192,7 @@ namespace Umbraco.Core.Services
public IEnumerable<EntityContainer> GetMediaTypeContainers(int[] containerIds)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid);
return repo.GetAll(containerIds);
@@ -207,7 +201,7 @@ namespace Umbraco.Core.Services
public IEnumerable<EntityContainer> GetMediaTypeContainers(string name, int level)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid);
return repo.Get(name, level);
@@ -236,7 +230,7 @@ namespace Umbraco.Core.Services
public IEnumerable<EntityContainer> GetContentTypeContainers(int[] containerIds)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid);
return repo.GetAll(containerIds);
@@ -265,7 +259,7 @@ namespace Umbraco.Core.Services
private EntityContainer GetContainer(Guid containerId, Guid containerObjectType)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType);
return repo.Get(containerId);
@@ -274,7 +268,7 @@ namespace Umbraco.Core.Services
public IEnumerable<EntityContainer> GetContentTypeContainers(string name, int level)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid);
return repo.Get(name, level);
@@ -288,7 +282,11 @@ namespace Umbraco.Core.Services
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid);
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs); // fixme commit?
if (container == null)
{
uow.Commit();
return OperationStatus.NoOperation(evtMsgs);
}
if (uow.Events.DispatchCancelable(DeletingContentTypeContainer, this, new DeleteEventArgs<EntityContainer>(container, evtMsgs)))
{
@@ -314,7 +312,11 @@ namespace Umbraco.Core.Services
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid);
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs); // fixme commit?
if (container == null)
{
uow.Commit();
return OperationStatus.NoOperation(evtMsgs);
}
if (uow.Events.DispatchCancelable(DeletingMediaTypeContainer, this, new DeleteEventArgs<EntityContainer>(container, evtMsgs)))
{
@@ -340,7 +342,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<string> GetAllPropertyTypeAliases()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.GetAllPropertyTypeAliases();
@@ -357,7 +359,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.GetAllContentTypeAliases(objectTypes);
@@ -454,7 +456,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.Get(id);
@@ -468,7 +470,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.Get(alias);
@@ -482,7 +484,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.Get(id);
@@ -496,7 +498,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.GetAll(ids);
@@ -510,7 +512,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.GetAll(ids.ToArray());
@@ -524,7 +526,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
@@ -539,7 +541,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
@@ -557,7 +559,7 @@ namespace Umbraco.Core.Services
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
@@ -573,7 +575,7 @@ namespace Umbraco.Core.Services
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
@@ -584,6 +586,27 @@ namespace Umbraco.Core.Services
}
}
public override IEnumerable<IContentTypeBase> GetDescendants(IContentTypeBase contentType)
{
var ctype = contentType as IContentType;
if (ctype != null) return GetDescendants(ctype);
var mtype = contentType as IMediaType;
if (mtype != null) return GetDescendants(mtype);
return Enumerable.Empty<IContentTypeBase>();
}
public IEnumerable<IContentType> GetDescendants(IContentType contentType)
{
return GetContentTypeChildren(contentType.Id)
.SelectRecursive(type => GetContentTypeChildren(type.Id));
}
public IEnumerable<IMediaType> GetDescendants(IMediaType contentType)
{
return GetMediaTypeChildren(contentType.Id)
.SelectRecursive(type => GetMediaTypeChildren(type.Id));
}
/// <summary>
/// This is called after an IContentType is saved and is used to update the content xml structures in the database
/// if they are required to be updated.
@@ -591,42 +614,39 @@ namespace Umbraco.Core.Services
/// <param name="contentTypes">A tuple of a content type and a boolean indicating if it is new (HasIdentity was false before committing)</param>
private void UpdateContentXmlStructure(params IContentTypeBase[] contentTypes)
{
var toUpdate = GetContentTypesForXmlUpdates(contentTypes).ToArray();
if (toUpdate.Any())
if (toUpdate.Any() == false) return;
var firstType = toUpdate.First();
//if it is a content type then call the rebuilding methods or content
if (firstType is IContentType)
{
var firstType = toUpdate.First();
//if it is a content type then call the rebuilding methods or content
if (firstType is IContentType)
var typedContentService = _contentService as ContentService;
if (typedContentService != null)
{
var typedContentService = _contentService as ContentService;
if (typedContentService != null)
{
typedContentService.RePublishAll(toUpdate.Select(x => x.Id).ToArray());
}
else
{
//this should never occur, the content service should always be typed but we'll check anyways.
_contentService.RePublishAll();
}
typedContentService.RePublishAll(toUpdate.Select(x => x.Id).ToArray());
}
else if (firstType is IMediaType)
else
{
//if it is a media type then call the rebuilding methods for media
var typedContentService = _mediaService as MediaService;
if (typedContentService != null)
{
typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray());
}
//this should never occur, the content service should always be typed but we'll check anyways.
_contentService.RePublishAll();
}
}
else if (firstType is IMediaType)
{
//if it is a media type then call the rebuilding methods for media
var typedContentService = _mediaService as MediaService;
if (typedContentService != null)
{
typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray());
}
}
}
public int CountContentTypes()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
return repository.Count(Query<IContentType>.Builder);
@@ -635,7 +655,7 @@ namespace Umbraco.Core.Services
public int CountMediaTypes()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
return repository.Count(Query<IMediaType>.Builder);
@@ -753,16 +773,15 @@ namespace Umbraco.Core.Services
repository.AddOrUpdate(contentType);
uow.Commit();
}
UpdateContentXmlStructure(contentType); // fixme wtf here?
UpdateContentXmlStructure(contentType);
uow.Events.Dispatch(SavedContentType, this, new SaveEventArgs<IContentType>(contentType, false));
Audit(uow, AuditType.Save, "Save ContentType performed by user", userId, contentType.Id);
uow.Commit();
}
}
using (var scope = UowProvider.ScopeProvider.CreateScope()) // fixme what a mess
{
scope.Events.Dispatch(SavedContentType, this, new SaveEventArgs<IContentType>(contentType, false));
scope.Complete();
}
Audit(AuditType.Save, "Save ContentType performed by user", userId, contentType.Id);
}
/// <summary>
@@ -783,7 +802,7 @@ namespace Umbraco.Core.Services
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
foreach (var contentType in asArray)
@@ -798,16 +817,15 @@ namespace Umbraco.Core.Services
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray()); // fixme wtf
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
uow.Events.Dispatch(SavedContentType, this, new SaveEventArgs<IContentType>(asArray, false));
Audit(uow, AuditType.Save, "Save ContentTypes performed by user", userId, -1);
uow.Commit();
}
}
using (var scope = UowProvider.ScopeProvider.CreateScope()) // fixme what a mess
{
scope.Events.Dispatch(SavedContentType, this, new SaveEventArgs<IContentType>(asArray, false));
scope.Complete();
}
Audit(AuditType.Save, "Save ContentTypes performed by user", userId, -1);
}
/// <summary>
@@ -817,7 +835,7 @@ namespace Umbraco.Core.Services
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
public void Delete(IContentType contentType, int userId = 0)
{
{
using (new WriteLock(Locker))
{
using (var uow = UowProvider.GetUnitOfWork())
@@ -829,20 +847,20 @@ namespace Umbraco.Core.Services
}
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
//If we are deleting this content type, we are also deleting it's descendents!
var deletedContentTypes = new List<IContentType>() {contentType};
deletedContentTypes.AddRange(contentType.Descendants((IContentTypeService)this).OfType<IContentType>());
var deletedContentTypes = new List<IContentType> {contentType};
deletedContentTypes.AddRange(GetDescendants(contentType));
_contentService.DeleteContentOfTypes(deletedContentTypes.Select(x => x.Id), userId);
repository.Delete(contentType);
uow.Commit();
uow.Events.Dispatch(DeletedContentType, this, new DeleteEventArgs<IContentType>(deletedContentTypes.DistinctBy(x => x.Id), false));
}
Audit(AuditType.Delete, string.Format("Delete ContentType performed by user"), userId, contentType.Id);
Audit(uow, AuditType.Delete, string.Format("Delete ContentType performed by user"), userId, contentType.Id);
uow.Commit();
}
}
}
@@ -857,7 +875,7 @@ namespace Umbraco.Core.Services
public void Delete(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
using (new WriteLock(Locker))
{
using (var uow = UowProvider.GetUnitOfWork())
@@ -874,22 +892,21 @@ namespace Umbraco.Core.Services
var deletedContentTypes = new List<IContentType>(asArray);
foreach (var contentType in asArray)
{
deletedContentTypes.AddRange(contentType.Descendants((IContentTypeService)this).OfType<IContentType>());
deletedContentTypes.AddRange(GetDescendants(contentType));
}
_contentService.DeleteContentOfTypes(deletedContentTypes.Select(x => x.Id), userId);
_contentService.DeleteContentOfTypes(deletedContentTypes.Select(x => x.Id), userId);
foreach (var contentType in asArray)
{
repository.Delete(contentType);
}
uow.Commit();
uow.Events.Dispatch(DeletedContentType, this, new DeleteEventArgs<IContentType>(deletedContentTypes.DistinctBy(x => x.Id), false));
}
Audit(AuditType.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1);
Audit(uow, AuditType.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1);
uow.Commit();
}
}
}
@@ -900,7 +917,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
return repository.Get(id);
@@ -914,7 +931,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
return repository.Get(alias);
@@ -928,7 +945,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
return repository.Get(id);
@@ -942,7 +959,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
return repository.GetAll(ids);
@@ -956,7 +973,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
return repository.GetAll(ids.ToArray());
@@ -970,7 +987,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
@@ -985,7 +1002,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
var found = GetMediaType(id);
@@ -1002,7 +1019,7 @@ namespace Umbraco.Core.Services
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
@@ -1017,7 +1034,7 @@ namespace Umbraco.Core.Services
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
var found = GetMediaType(id);
@@ -1035,7 +1052,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(MovingMediaType, this, new MoveEventArgs<IMediaType>(evtMsgs, new MoveEventInfo<IMediaType>(toMove, toMove.Path, containerId))))
{
uow.Commit();
return Attempt.Fail(new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid);
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
@@ -1052,8 +1072,8 @@ namespace Umbraco.Core.Services
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
uow.Commit();
return Attempt.Fail(new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
}
uow.Commit();
uow.Events.Dispatch(MovedMediaType, this, new MoveEventArgs<IMediaType>(false, evtMsgs, moveInfo.ToArray()));
@@ -1071,7 +1091,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(MovingContentType, this, new MoveEventArgs<IContentType>(evtMsgs, new MoveEventInfo<IContentType>(toMove, toMove.Path, containerId))))
{
uow.Commit();
return Attempt.Fail(new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid);
var repository = RepositoryFactory.CreateContentTypeRepository(uow);
@@ -1088,8 +1111,8 @@ namespace Umbraco.Core.Services
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
uow.Commit();
return Attempt.Fail(new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
}
uow.Commit();
uow.Events.Dispatch(MovedContentType, this, new MoveEventArgs<IContentType>(false, evtMsgs, moveInfo.ToArray()));
@@ -1135,6 +1158,7 @@ namespace Umbraco.Core.Services
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
uow.Commit();
return Attempt.Fail(new OperationStatus<IMediaType, MoveOperationStatusType>(null, ex.Operation, evtMsgs));
}
uow.Commit();
@@ -1179,6 +1203,7 @@ namespace Umbraco.Core.Services
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
uow.Commit();
return Attempt.Fail(new OperationStatus<IContentType, MoveOperationStatusType>(null, ex.Operation, evtMsgs));
}
uow.Commit();
@@ -1203,23 +1228,21 @@ namespace Umbraco.Core.Services
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
ValidateLocked(mediaType); // throws if invalid
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
uow.Commit();
}
UpdateContentXmlStructure(mediaType); // fixme wtf
UpdateContentXmlStructure(mediaType);
using (var scope = UowProvider.ScopeProvider.CreateScope()) // fixme what a mess
{
scope.Events.Dispatch(SavedMediaType, this, new SaveEventArgs<IMediaType>(mediaType, false));
scope.Complete();
uow.Events.Dispatch(SavedMediaType, this, new SaveEventArgs<IMediaType>(mediaType, false));
Audit(uow, AuditType.Save, "Save MediaType performed by user", userId, mediaType.Id);
uow.Commit();
}
Audit(AuditType.Save, "Save MediaType performed by user", userId, mediaType.Id);
}
}
@@ -1231,7 +1254,7 @@ namespace Umbraco.Core.Services
public void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
using (new WriteLock(Locker))
{
using (var uow = UowProvider.GetUnitOfWork())
@@ -1241,7 +1264,7 @@ namespace Umbraco.Core.Services
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
foreach (var mediaType in asArray)
@@ -1256,15 +1279,14 @@ namespace Umbraco.Core.Services
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray()); // fixme wtf
using (var scope = UowProvider.ScopeProvider.CreateScope()) // fixme what a mess
{
scope.Events.Dispatch(SavedMediaType, this, new SaveEventArgs<IMediaType>(asArray, false));
scope.Complete();
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
uow.Events.Dispatch(SavedMediaType, this, new SaveEventArgs<IMediaType>(asArray, false));
Audit(uow, AuditType.Save, "Save MediaTypes performed by user", userId, -1);
uow.Commit();
}
Audit(AuditType.Save, "Save MediaTypes performed by user", userId, -1);
}
}
@@ -1292,17 +1314,17 @@ namespace Umbraco.Core.Services
//If we are deleting this content type, we are also deleting it's descendents!
var deletedMediaTypes = new List<IMediaType> { mediaType };
deletedMediaTypes.AddRange(mediaType.Descendants((IContentTypeService)this).OfType<IMediaType>());
deletedMediaTypes.AddRange(GetDescendants(mediaType));
_mediaService.DeleteMediaOfTypes(deletedMediaTypes.Select(x => x.Id), userId);
repository.Delete(mediaType);
uow.Commit();
uow.Events.Dispatch(DeletedMediaType, this, new DeleteEventArgs<IMediaType>(deletedMediaTypes.DistinctBy(x => x.Id), false));
}
Audit(AuditType.Delete, "Delete MediaType performed by user", userId, mediaType.Id);
Audit(uow, AuditType.Delete, "Delete MediaType performed by user", userId, mediaType.Id);
uow.Commit();
}
}
}
@@ -1317,7 +1339,7 @@ namespace Umbraco.Core.Services
//TODO: Share all of this logic with the Delete IContentType methods, no need for code duplication
var asArray = mediaTypes.ToArray();
using (new WriteLock(Locker))
{
using (var uow = UowProvider.GetUnitOfWork())
@@ -1329,12 +1351,12 @@ namespace Umbraco.Core.Services
}
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
//If we are deleting this content type, we are also deleting it's descendents!
var deletedMediaTypes = new List<IMediaType>(asArray);
foreach (var mediaType in asArray)
{
deletedMediaTypes.AddRange(mediaType.Descendants((IContentTypeService)this).OfType<IMediaType>());
deletedMediaTypes.AddRange(GetDescendants(mediaType));
}
_mediaService.DeleteMediaOfTypes(deletedMediaTypes.Select(x => x.Id), userId);
@@ -1344,12 +1366,11 @@ namespace Umbraco.Core.Services
repository.Delete(mediaType);
}
uow.Commit();
uow.Events.Dispatch(DeletedMediaType, this, new DeleteEventArgs<IMediaType>(deletedMediaTypes.DistinctBy(x => x.Id), false));
}
Audit(AuditType.Delete, "Delete MediaTypes performed by user", userId, -1);
Audit(uow, AuditType.Delete, "Delete MediaTypes performed by user", userId, -1);
uow.Commit();
}
}
}
@@ -1408,14 +1429,10 @@ namespace Umbraco.Core.Services
return dtd.ToString();
}
private void Audit(AuditType type, string message, int userId, int objectId)
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var auditRepo = RepositoryFactory.CreateAuditRepository(uow);
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
var auditRepo = RepositoryFactory.CreateAuditRepository(uow);
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
#region Event Handlers
@@ -13,9 +13,8 @@ namespace Umbraco.Core.Services
{
public ContentTypeServiceBase(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
}
{ }
/// <summary>
/// This is called after an content type is saved and is used to update the content xml structures in the database
/// if they are required to be updated.
@@ -33,7 +32,7 @@ namespace Umbraco.Core.Services
// - a content type changes it's alias OR
// - if a content type has it's property removed OR
// - if a content type has a property whose alias has changed
//here we need to check if the alias of the content type changed or if one of the properties was removed.
//here we need to check if the alias of the content type changed or if one of the properties was removed.
var dirty = contentType as IRememberBeingDirty;
if (dirty == null) continue;
@@ -50,25 +49,30 @@ namespace Umbraco.Core.Services
&& (dirty.WasPropertyDirty("Alias") || dirty.WasPropertyDirty("HasPropertyTypeBeenRemoved") || hasAnyPropertiesChangedAlias))
{
//If the alias was changed then we only need to update the xml structures for content of the current content type.
//If a property was deleted or a property alias was changed then we need to update the xml structures for any
//If a property was deleted or a property alias was changed then we need to update the xml structures for any
// content of the current content type and any of the content type's child content types.
if (dirty.WasPropertyDirty("Alias")
&& dirty.WasPropertyDirty("HasPropertyTypeBeenRemoved") == false && hasAnyPropertiesChangedAlias == false)
{
//if only the alias changed then only update the current content type
//if only the alias changed then only update the current content type
toUpdate.Add(contentType);
}
else
{
//if a property was deleted or alias changed, then update all content of the current content type
// and all of it's desscendant doc types.
toUpdate.AddRange(contentType.DescendantsAndSelf(this));
// and all of it's desscendant doc types.
toUpdate.Add(contentType);
toUpdate.AddRange(GetDescendants(contentType));
}
}
}
return toUpdate;
}
public virtual IEnumerable<IContentTypeBase> GetDescendants(IContentTypeBase contentType)
{
return Enumerable.Empty<IContentTypeBase>();
}
}
}
+32 -33
View File
@@ -66,7 +66,7 @@ namespace Umbraco.Core.Services
public EntityContainer GetContainer(int containerId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.Get(containerId);
@@ -75,7 +75,7 @@ namespace Umbraco.Core.Services
public EntityContainer GetContainer(Guid containerId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.Get(containerId);
@@ -84,7 +84,7 @@ namespace Umbraco.Core.Services
public IEnumerable<EntityContainer> GetContainers(string name, int level)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.Get(name, level);
@@ -108,7 +108,7 @@ namespace Umbraco.Core.Services
public IEnumerable<EntityContainer> GetContainers(int[] containerIds)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.GetAll(containerIds);
@@ -181,7 +181,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionByName(string name)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetByQuery(new Query<IDataTypeDefinition>().Where(x => x.Name == name)).FirstOrDefault();
@@ -195,7 +195,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.Get(id);
@@ -209,7 +209,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionById(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
var query = Query<IDataTypeDefinition>.Builder.Where(x => x.Key == id);
@@ -238,7 +238,7 @@ namespace Umbraco.Core.Services
/// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns>
public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
var query = Query<IDataTypeDefinition>.Builder.Where(x => x.PropertyEditorAlias == propertyEditorAlias);
@@ -253,7 +253,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="IDataTypeDefinition"/> objects</returns>
public IEnumerable<IDataTypeDefinition> GetAllDataTypeDefinitions(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetAll(ids);
@@ -267,7 +267,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of string values</returns>
public IEnumerable<string> GetPreValuesByDataTypeId(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
//now convert the collection to a string list
@@ -284,7 +284,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public PreValueCollection GetPreValuesCollectionByDataTypeId(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetPreValuesCollectionByDataTypeId(id);
@@ -298,7 +298,7 @@ namespace Umbraco.Core.Services
/// <returns>PreValue as a string</returns>
public string GetPreValueAsString(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetPreValueAsString(id);
@@ -313,7 +313,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Moving, this, new MoveEventArgs<IDataTypeDefinition>(evtMsgs, new MoveEventInfo<IDataTypeDefinition>(toMove, toMove.Path, parentId))))
{
uow.Commit();
return Attempt.Fail(new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
@@ -366,13 +369,12 @@ namespace Umbraco.Core.Services
dataTypeDefinition.CreatorId = userId;
repository.AddOrUpdate(dataTypeDefinition);
uow.Commit();
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false));
}
// FIXME transaction!
Audit(AuditType.Save, "Save DataTypeDefinition performed by user", userId, dataTypeDefinition.Id);
Audit(uow, AuditType.Save, "Save DataTypeDefinition performed by user", userId, dataTypeDefinition.Id);
uow.Commit();
}
}
/// <summary>
@@ -411,13 +413,13 @@ namespace Umbraco.Core.Services
dataTypeDefinition.CreatorId = userId;
repository.AddOrUpdate(dataTypeDefinition);
}
uow.Commit();
if (raiseEvents)
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions, false));
}
Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, -1);
Audit(uow, AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -487,7 +489,6 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
repository.AddOrUpdatePreValues(dataTypeDefinition, values);
uow.Commit();
}
@@ -504,7 +505,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition)))
{
uow.Commit();
return;
}
// if preValues contain the data type, override the data type definition accordingly
if (values != null && values.ContainsKey(Constants.PropertyEditors.PreValueKeys.DataValueType))
@@ -520,12 +524,11 @@ namespace Umbraco.Core.Services
//add/update the prevalues
repository.AddOrUpdatePreValues(dataTypeDefinition, values);
Audit(uow, AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id);
uow.Commit();
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false));
}
Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id);
}
/// <summary>
@@ -542,18 +545,20 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition)))
{
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
repository.Delete(dataTypeDefinition);
Audit(uow, AuditType.Delete, "Delete DataTypeDefinition performed by user", userId, dataTypeDefinition.Id);
uow.Commit();
uow.Events.Dispatch(Deleted, this, new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition, false));
}
Audit(AuditType.Delete, "Delete DataTypeDefinition performed by user", userId, dataTypeDefinition.Id);
}
/// <summary>
@@ -577,14 +582,10 @@ namespace Umbraco.Core.Services
return DataTypesResolver.Current.DataTypes;
}
private void Audit(AuditType type, string message, int userId, int objectId)
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var auditRepo = RepositoryFactory.CreateAuditRepository(uow);
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
var auditRepo = RepositoryFactory.CreateAuditRepository(uow);
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
#region Event Handlers
@@ -624,7 +625,5 @@ namespace Umbraco.Core.Services
/// </summary>
public static event TypedEventHandler<IDataTypeService, MoveEventArgs<IDataTypeDefinition>> Moved;
#endregion
}
}
+11 -5
View File
@@ -19,7 +19,7 @@ namespace Umbraco.Core.Services
public bool Exists(string domainName)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateDomainRepository(uow);
return repo.Exists(domainName);
@@ -33,7 +33,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<IDomain>(domain, evtMsgs)))
{
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
var repository = RepositoryFactory.CreateDomainRepository(uow);
repository.Delete(domain);
@@ -49,7 +52,7 @@ namespace Umbraco.Core.Services
public IDomain GetByName(string name)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDomainRepository(uow);
return repository.GetByName(name);
@@ -58,7 +61,7 @@ namespace Umbraco.Core.Services
public IDomain GetById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateDomainRepository(uow);
return repo.Get(id);
@@ -67,7 +70,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IDomain> GetAll(bool includeWildcards)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateDomainRepository(uow);
return repo.GetAll(includeWildcards);
@@ -76,7 +79,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IDomain> GetAssignedDomains(int contentId, bool includeWildcards)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateDomainRepository(uow);
return repo.GetAssignedDomains(contentId, includeWildcards);
@@ -90,7 +93,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IDomain>(domainEntity, evtMsgs)))
{
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
var repository = RepositoryFactory.CreateDomainRepository(uow);
repository.AddOrUpdate(domainEntity);
+2 -2
View File
@@ -647,7 +647,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="UmbracoObjectTypes"/></returns>
public virtual UmbracoObjectTypes GetObjectType(int id)
{
using (var uow = UowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var sql = new Sql().Select("nodeObjectType").From<NodeDto>().Where<NodeDto>(x => x.NodeId == id);
var nodeObjectTypeId = uow.Database.ExecuteScalar<Guid>(sql);
@@ -663,7 +663,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="UmbracoObjectTypes"/></returns>
public virtual UmbracoObjectTypes GetObjectType(Guid key)
{
using (var uow = UowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var sql = new Sql().Select("nodeObjectType").From<NodeDto>().Where<NodeDto>(x => x.UniqueId == key);
var nodeObjectTypeId = uow.Database.ExecuteScalar<Guid>(sql);
+108 -122
View File
@@ -15,31 +15,21 @@ using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
// note
// file unit of work are just IUnitOfWork which is not IDisposable
// they don't really participate in the scope etc ;(
// FIXME not anymore now that Shan's made FileUnitOfWork a normal UOW? then WTF?
/// <summary>
/// Represents the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates
/// </summary>
public class FileService : ScopeRepositoryService, IFileService
{
private readonly IScopeUnitOfWorkProvider _fileUowProvider;
private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoTemplatePage";
private const string PartialViewMacroHeader = "@inherits Umbraco.Web.Macros.PartialViewMacroPage";
public FileService(
IScopeUnitOfWorkProvider fileProvider,
IDatabaseUnitOfWorkProvider dataProvider,
IDatabaseUnitOfWorkProvider provider,
RepositoryFactory repositoryFactory,
ILogger logger,
IEventMessagesFactory eventMessagesFactory)
: base(dataProvider, repositoryFactory, logger, eventMessagesFactory)
{
_fileUowProvider = fileProvider;
}
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{ }
#region Stylesheets
@@ -50,11 +40,9 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Stylesheet"/> objects</returns>
public IEnumerable<Stylesheet> GetStylesheets(params string[] names)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
// FIXME is it ok to use the same UOW here twice?
// review everywhere in this file!!
var repository = RepositoryFactory.CreateStylesheetRepository(uow, uow);
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
return repository.GetAll(names);
}
}
@@ -66,9 +54,9 @@ namespace Umbraco.Core.Services
/// <returns>A <see cref="Stylesheet"/> object</returns>
public Stylesheet GetStylesheetByName(string name)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateStylesheetRepository(uow, uow);
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
return repository.Get(name);
}
}
@@ -88,13 +76,14 @@ namespace Umbraco.Core.Services
return;
}
var repository = RepositoryFactory.CreateStylesheetRepository(uow, uow);
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
repository.AddOrUpdate(stylesheet);
uow.Commit();
uow.Events.Dispatch(SavedStylesheet, this, new SaveEventArgs<Stylesheet>(stylesheet, false));
}
Audit(AuditType.Save, "Save Stylesheet performed by user", userId, -1);
uow.Events.Dispatch(SavedStylesheet, this, new SaveEventArgs<Stylesheet>(stylesheet, false));
Audit(uow, AuditType.Save, "Save Stylesheet performed by user", userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -106,7 +95,7 @@ namespace Umbraco.Core.Services
{
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateStylesheetRepository(uow, uow);
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
var stylesheet = repository.Get(path);
if (stylesheet == null)
{
@@ -121,12 +110,12 @@ namespace Umbraco.Core.Services
}
repository.Delete(stylesheet);
uow.Commit();
uow.Events.Dispatch(DeletedStylesheet, this, new DeleteEventArgs<Stylesheet>(stylesheet, false));
}
Audit(AuditType.Delete, string.Format("Delete Stylesheet performed by user"), userId, -1);
Audit(uow, AuditType.Delete, string.Format("Delete Stylesheet performed by user"), userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -136,9 +125,9 @@ namespace Umbraco.Core.Services
/// <returns>True if Stylesheet is valid, otherwise false</returns>
public bool ValidateStylesheet(Stylesheet stylesheet)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateStylesheetRepository(uow, uow);
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
return repository.ValidateStylesheet(stylesheet);
}
}
@@ -152,7 +141,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Script"/> objects</returns>
public IEnumerable<Script> GetScripts(params string[] names)
{
using (var uow = _fileUowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
return repository.GetAll(names);
@@ -166,7 +155,7 @@ namespace Umbraco.Core.Services
/// <returns>A <see cref="Script"/> object</returns>
public Script GetScriptByName(string name)
{
using (var uow = _fileUowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
return repository.Get(name);
@@ -180,7 +169,7 @@ namespace Umbraco.Core.Services
/// <param name="userId"></param>
public void SaveScript(Script script, int userId = 0)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(SavingScript, this, new SaveEventArgs<Script>(script)))
{
@@ -190,12 +179,12 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateScriptRepository(uow);
repository.AddOrUpdate(script);
uow.Commit();
uow.Events.Dispatch(SavedScript, this, new SaveEventArgs<Script>(script, false));
}
Audit(AuditType.Save, "Save Script performed by user", userId, -1);
Audit(uow, AuditType.Save, "Save Script performed by user", userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -205,7 +194,7 @@ namespace Umbraco.Core.Services
/// <param name="userId"></param>
public void DeleteScript(string path, int userId = 0)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
var script = repository.Get(path);
@@ -222,12 +211,12 @@ namespace Umbraco.Core.Services
}
repository.Delete(script);
uow.Commit();
uow.Events.Dispatch(DeletedScript, this, new DeleteEventArgs<Script>(script, false));
}
Audit(AuditType.Delete, string.Format("Delete Script performed by user"), userId, -1);
Audit(uow, AuditType.Delete, string.Format("Delete Script performed by user"), userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -237,7 +226,7 @@ namespace Umbraco.Core.Services
/// <returns>True if Script is valid, otherwise false</returns>
public bool ValidateScript(Script script)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
return repository.ValidateScript(script);
@@ -246,7 +235,7 @@ namespace Umbraco.Core.Services
public void CreateScriptFolder(string folderPath)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
((ScriptRepository)repository).AddFolder(folderPath);
@@ -256,7 +245,7 @@ namespace Umbraco.Core.Services
public void DeleteScriptFolder(string folderPath)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
((ScriptRepository)repository).DeleteFolder(folderPath);
@@ -308,12 +297,12 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateTemplateRepository(uow);
repository.AddOrUpdate(template);
uow.Commit();
uow.Events.Dispatch(SavedTemplate, this, new SaveEventArgs<ITemplate>(template, false, evtMsgs));
}
Audit(AuditType.Save, "Save Template performed by user", userId, template.Id);
Audit(uow, AuditType.Save, "Save Template performed by user", userId, template.Id);
uow.Commit();
}
return Attempt.Succeed(new OperationStatus<ITemplate, OperationStatusType>(template, OperationStatusType.Success, evtMsgs));
}
@@ -338,7 +327,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
public IEnumerable<ITemplate> GetTemplates(params string[] aliases)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetAll(aliases).OrderBy(x => x.Name);
@@ -351,7 +340,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
public IEnumerable<ITemplate> GetTemplates(int masterTemplateId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetChildren(masterTemplateId).OrderBy(x => x.Name);
@@ -365,7 +354,7 @@ namespace Umbraco.Core.Services
/// <returns>The <see cref="ITemplate"/> object matching the alias, or null.</returns>
public ITemplate GetTemplate(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.Get(alias);
@@ -379,7 +368,7 @@ namespace Umbraco.Core.Services
/// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns>
public ITemplate GetTemplate(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.Get(id);
@@ -393,7 +382,7 @@ namespace Umbraco.Core.Services
/// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns>
public ITemplate GetTemplate(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
var query = Query<ITemplate>.Builder.Where(x => x.Key == id);
@@ -403,7 +392,7 @@ namespace Umbraco.Core.Services
public IEnumerable<ITemplate> GetTemplateDescendants(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetDescendants(alias);
@@ -417,7 +406,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<ITemplate> GetTemplateDescendants(int masterTemplateId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetDescendants(masterTemplateId);
@@ -431,7 +420,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<ITemplate> GetTemplateChildren(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetChildren(alias);
@@ -445,7 +434,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<ITemplate> GetTemplateChildren(int masterTemplateId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetChildren(masterTemplateId);
@@ -461,7 +450,7 @@ namespace Umbraco.Core.Services
[EditorBrowsable(EditorBrowsableState.Never)]
public TemplateNode GetTemplateNode(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetTemplateNode(alias);
@@ -478,7 +467,7 @@ namespace Umbraco.Core.Services
[EditorBrowsable(EditorBrowsableState.Never)]
public TemplateNode FindTemplateInTree(TemplateNode anyNode, string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.FindTemplateInTree(anyNode, alias);
@@ -502,12 +491,12 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateTemplateRepository(uow);
repository.AddOrUpdate(template);
uow.Commit();
uow.Events.Dispatch(SavedTemplate, this, new SaveEventArgs<ITemplate>(template, false));
}
Audit(AuditType.Save, "Save Template performed by user", userId, template.Id);
Audit(uow, AuditType.Save, "Save Template performed by user", userId, template.Id);
uow.Commit();
}
}
/// <summary>
@@ -529,12 +518,12 @@ namespace Umbraco.Core.Services
{
repository.AddOrUpdate(template);
}
uow.Commit();
uow.Events.Dispatch(SavedTemplate, this, new SaveEventArgs<ITemplate>(templates, false));
}
Audit(AuditType.Save, "Save Template performed by user", userId, -1);
Audit(uow, AuditType.Save, "Save Template performed by user", userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -552,7 +541,7 @@ namespace Umbraco.Core.Services
/// </remarks>
public RenderingEngine DetermineTemplateRenderingEngine(ITemplate template)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.DetermineTemplateRenderingEngine(template);
@@ -566,12 +555,10 @@ namespace Umbraco.Core.Services
/// <param name="userId"></param>
public void DeleteTemplate(string alias, int userId = 0)
{
// fixme - WHY outside of UOW?!
// v8 - that should be part of the uow / scope
var template = GetTemplate(alias);
if (template == null)
{
return;
}
using (var uow = UowProvider.GetUnitOfWork())
{
@@ -584,12 +571,12 @@ namespace Umbraco.Core.Services
}
repository.Delete(template);
uow.Commit();
uow.Events.Dispatch(DeletedTemplate, this, new DeleteEventArgs<ITemplate>(template, false));
}
Audit(AuditType.Delete, "Delete Template performed by user", userId, template.Id);
Audit(uow, AuditType.Delete, "Delete Template performed by user", userId, template.Id);
uow.Commit();
}
}
/// <summary>
@@ -599,7 +586,7 @@ namespace Umbraco.Core.Services
/// <returns>True if Script is valid, otherwise false</returns>
public bool ValidateTemplate(ITemplate template)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.ValidateTemplate(template);
@@ -608,7 +595,7 @@ namespace Umbraco.Core.Services
public Stream GetTemplateFileContentStream(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetFileContentStream(filepath);
@@ -617,17 +604,17 @@ namespace Umbraco.Core.Services
public void SetTemplateFileContent(string filepath, Stream content)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
repository.SetFileContent(filepath, content);
// fixme - no need to commit... always committing?????
uow.Commit();
}
}
public long GetTemplateFileSize(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateTemplateRepository(uow);
return repository.GetFileSize(filepath);
@@ -638,7 +625,7 @@ namespace Umbraco.Core.Services
public Stream GetStylesheetFileContentStream(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
return repository.GetFileContentStream(filepath);
@@ -647,16 +634,17 @@ namespace Umbraco.Core.Services
public void SetStylesheetFileContent(string filepath, Stream content)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
repository.SetFileContent(filepath, content);
uow.Commit();
}
}
public long GetStylesheetFileSize(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateStylesheetRepository(uow);
return repository.GetFileSize(filepath);
@@ -665,7 +653,7 @@ namespace Umbraco.Core.Services
public Stream GetScriptFileContentStream(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
return repository.GetFileContentStream(filepath);
@@ -674,16 +662,17 @@ namespace Umbraco.Core.Services
public void SetScriptFileContent(string filepath, Stream content)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
repository.SetFileContent(filepath, content);
uow.Commit();
}
}
public long GetScriptFileSize(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateScriptRepository(uow);
return repository.GetFileSize(filepath);
@@ -692,7 +681,7 @@ namespace Umbraco.Core.Services
public Stream GetXsltFileContentStream(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateXsltFileRepository(uow);
return repository.GetFileContentStream(filepath);
@@ -701,16 +690,17 @@ namespace Umbraco.Core.Services
public void SetXsltFileContent(string filepath, Stream content)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateXsltFileRepository(uow);
repository.SetFileContent(filepath, content);
uow.Commit();
}
}
public long GetXsltFileSize(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateXsltFileRepository(uow);
return repository.GetFileSize(filepath);
@@ -737,9 +727,9 @@ namespace Umbraco.Core.Services
public void CreatePartialViewFolder(string folderPath)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreatePartialViewRepository(uow))
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreatePartialViewRepository(uow);
((PartialViewRepository)repository).AddFolder(folderPath);
uow.Commit();
}
@@ -747,9 +737,9 @@ namespace Umbraco.Core.Services
public void CreatePartialViewMacroFolder(string folderPath)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow))
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow);
((PartialViewMacroRepository)repository).AddFolder(folderPath);
uow.Commit();
}
@@ -757,7 +747,7 @@ namespace Umbraco.Core.Services
public void DeletePartialViewFolder(string folderPath)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreatePartialViewRepository(uow);
((PartialViewRepository)repository).DeleteFolder(folderPath);
@@ -767,7 +757,7 @@ namespace Umbraco.Core.Services
public void DeletePartialViewMacroFolder(string folderPath)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow);
((PartialViewMacroRepository)repository).DeleteFolder(folderPath);
@@ -777,7 +767,7 @@ namespace Umbraco.Core.Services
public IPartialView GetPartialView(string path)
{
using (var uow = _fileUowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreatePartialViewRepository(uow);
return repository.Get(path);
@@ -786,7 +776,7 @@ namespace Umbraco.Core.Services
public IPartialView GetPartialViewMacro(string path)
{
using (var uow = _fileUowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow);
return repository.Get(path);
@@ -795,7 +785,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IPartialView> GetPartialViewMacros(params string[] names)
{
using (var uow = _fileUowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow);
return repository.GetAll(names).OrderBy(x => x.Name);
@@ -804,7 +794,7 @@ namespace Umbraco.Core.Services
public IXsltFile GetXsltFile(string path)
{
using (var uow = _fileUowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateXsltFileRepository(uow);
return repository.Get(path);
@@ -813,7 +803,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IXsltFile> GetXsltFiles(params string[] names)
{
using (var uow = _fileUowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateXsltFileRepository(uow);
return repository.GetAll(names).OrderBy(x => x.Name);
@@ -845,16 +835,16 @@ namespace Umbraco.Core.Services
}
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = GetPartialViewRepository(partialViewType, uow);
repository.AddOrUpdate(partialView);
uow.Commit();
uow.Events.Dispatch(CreatedPartialView, this, new NewEventArgs<IPartialView>(partialView, false, partialView.Alias, -1));
}
Audit(AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1);
Audit(uow, AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1);
uow.Commit();
}
return Attempt<IPartialView>.Succeed(partialView);
}
@@ -871,7 +861,7 @@ namespace Umbraco.Core.Services
private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int userId = 0)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = GetPartialViewRepository(partialViewType, uow);
var partialView = repository.Get(path);
@@ -888,12 +878,12 @@ namespace Umbraco.Core.Services
}
repository.Delete(partialView);
uow.Commit();
uow.Events.Dispatch(DeletedPartialView, this, new DeleteEventArgs<IPartialView>(partialView, false));
}
Audit(AuditType.Delete, string.Format("Delete {0} performed by user", partialViewType), userId, -1);
Audit(uow, AuditType.Delete, string.Format("Delete {0} performed by user", partialViewType), userId, -1);
uow.Commit();
}
return true;
@@ -911,7 +901,7 @@ namespace Umbraco.Core.Services
private Attempt<IPartialView> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int userId = 0)
{
using (var uow = _fileUowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(SavingPartialView, this, new SaveEventArgs<IPartialView>(partialView)))
{
@@ -921,18 +911,19 @@ namespace Umbraco.Core.Services
var repository = GetPartialViewRepository(partialViewType, uow);
repository.AddOrUpdate(partialView);
uow.Commit();
uow.Events.Dispatch(SavedPartialView, this, new SaveEventArgs<IPartialView>(partialView, false));
}
Audit(AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1);
uow.Events.Dispatch(SavedPartialView, this, new SaveEventArgs<IPartialView>(partialView, false));
Audit(uow, AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1);
uow.Commit();
}
return Attempt.Succeed(partialView);
}
public bool ValidatePartialView(PartialView partialView)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreatePartialViewRepository(uow);
return repository.ValidatePartialView(partialView);
@@ -941,7 +932,7 @@ namespace Umbraco.Core.Services
public bool ValidatePartialViewMacro(PartialView partialView)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow);
return repository.ValidatePartialView(partialView);
@@ -981,7 +972,7 @@ namespace Umbraco.Core.Services
public Stream GetPartialViewMacroFileContentStream(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = GetPartialViewRepository(PartialViewType.PartialViewMacro, uow);
return repository.GetFileContentStream(filepath);
@@ -1039,7 +1030,6 @@ namespace Umbraco.Core.Services
public void SetPartialViewMacroFileContent(string filepath, Stream content)
{
// FIXME FTW would we use a READONLY unit of work to SET FILE CONTENT
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = GetPartialViewRepository(PartialViewType.PartialViewMacro, uow);
@@ -1050,7 +1040,7 @@ namespace Umbraco.Core.Services
public long GetPartialViewMacroFileSize(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = GetPartialViewRepository(PartialViewType.PartialViewMacro, uow);
return repository.GetFileSize(filepath);
@@ -1059,7 +1049,7 @@ namespace Umbraco.Core.Services
public Stream GetPartialViewFileContentStream(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = GetPartialViewRepository(PartialViewType.PartialView, uow);
return repository.GetFileContentStream(filepath);
@@ -1078,7 +1068,7 @@ namespace Umbraco.Core.Services
public long GetPartialViewFileSize(string filepath)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = GetPartialViewRepository(PartialViewType.PartialView, uow);
return repository.GetFileSize(filepath);
@@ -1087,14 +1077,10 @@ namespace Umbraco.Core.Services
#endregion
private void Audit(AuditType type, string message, int userId, int objectId)
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
//TODO Method to change name and/or alias of view/masterpage template
@@ -1,14 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
@@ -18,12 +15,9 @@ namespace Umbraco.Core.Services
/// </summary>
public class LocalizationService : ScopeRepositoryService, ILocalizationService
{
public LocalizationService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
}
{ }
/// <summary>
/// Adds or updates a translation for a dictionary item and language
@@ -110,7 +104,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IDictionaryItem"/></returns>
public IDictionaryItem GetDictionaryItemById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
//ensure the lazy Language callback is assigned
@@ -128,7 +122,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="DictionaryItem"/></returns>
public IDictionaryItem GetDictionaryItemById(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
//ensure the lazy Language callback is assigned
@@ -146,7 +140,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IDictionaryItem"/></returns>
public IDictionaryItem GetDictionaryItemByKey(string key)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
//ensure the lazy Language callback is assigned
@@ -164,7 +158,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="IDictionaryItem"/> objects</returns>
public IEnumerable<IDictionaryItem> GetDictionaryItemChildren(Guid parentId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
var query = Query<IDictionaryItem>.Builder.Where(x => x.ParentId == parentId);
@@ -183,7 +177,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="IDictionaryItem"/> objects</returns>
public IEnumerable<IDictionaryItem> GetDictionaryItemDescendants(Guid? parentId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
//ensure the lazy Language callback is assigned
@@ -200,7 +194,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="IDictionaryItem"/> objects</returns>
public IEnumerable<IDictionaryItem> GetRootDictionaryItems()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
var query = Query<IDictionaryItem>.Builder.Where(x => x.ParentId == null);
@@ -219,7 +213,7 @@ namespace Umbraco.Core.Services
/// <returns>True if a <see cref="IDictionaryItem"/> exists, otherwise false</returns>
public bool DictionaryItemExists(string key)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
return repository.Get(key) != null;
@@ -242,14 +236,14 @@ namespace Umbraco.Core.Services
}
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
repository.AddOrUpdate(dictionaryItem);
uow.Commit();
//ensure the lazy Language callback is assigned
EnsureDictionaryItemLanguageCallback(dictionaryItem);
uow.Commit(); // FIXME do we need this? what's the func above doing?
uow.Events.Dispatch(SavedDictionaryItem, this, new SaveEventArgs<IDictionaryItem>(dictionaryItem, false));
}
Audit(AuditType.Save, "Save DictionaryItem performed by user", userId, dictionaryItem.Id);
// ensure the lazy Language callback is assigned (not using the uow)
EnsureDictionaryItemLanguageCallback(dictionaryItem);
uow.Events.Dispatch(SavedDictionaryItem, this, new SaveEventArgs<IDictionaryItem>(dictionaryItem, false));
Audit(uow, AuditType.Save, "Save DictionaryItem performed by user", userId, dictionaryItem.Id);
uow.Commit();
}
}
/// <summary>
@@ -270,11 +264,12 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateDictionaryRepository(uow);
repository.Delete(dictionaryItem);
uow.Commit();
uow.Events.Dispatch(DeletedDictionaryItem, this, new DeleteEventArgs<IDictionaryItem>(dictionaryItem, false));
}
Audit(AuditType.Delete, "Delete DictionaryItem performed by user", userId, dictionaryItem.Id);
uow.Events.Dispatch(DeletedDictionaryItem, this, new DeleteEventArgs<IDictionaryItem>(dictionaryItem, false));
Audit(uow, AuditType.Delete, "Delete DictionaryItem performed by user", userId, dictionaryItem.Id);
uow.Commit();
}
}
/// <summary>
@@ -284,7 +279,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="Language"/></returns>
public ILanguage GetLanguageById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateLanguageRepository(uow);
return repository.Get(id);
@@ -298,7 +293,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="Language"/></returns>
public ILanguage GetLanguageByCultureCode(string cultureName)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateLanguageRepository(uow);
return repository.GetByCultureName(cultureName);
@@ -312,7 +307,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="Language"/></returns>
public ILanguage GetLanguageByIsoCode(string isoCode)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateLanguageRepository(uow);
return repository.GetByIsoCode(isoCode);
@@ -325,7 +320,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="ILanguage"/> objects</returns>
public IEnumerable<ILanguage> GetAllLanguages()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateLanguageRepository(uow);
return repository.GetAll();
@@ -348,11 +343,12 @@ namespace Umbraco.Core.Services
}
var repository = RepositoryFactory.CreateLanguageRepository(uow);
repository.AddOrUpdate(language);
uow.Commit();
uow.Events.Dispatch(SavedLanguage, this, new SaveEventArgs<ILanguage>(language, false));
}
Audit(AuditType.Save, "Save Language performed by user", userId, language.Id);
uow.Events.Dispatch(SavedLanguage, this, new SaveEventArgs<ILanguage>(language, false));
Audit(uow, AuditType.Save, "Save Language performed by user", userId, language.Id);
uow.Commit();
}
}
/// <summary>
@@ -372,27 +368,24 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateLanguageRepository(uow);
repository.Delete(language);
uow.Commit();
uow.Events.Dispatch(DeletedLanguage, this, new DeleteEventArgs<ILanguage>(language, false));
}
Audit(AuditType.Delete, "Delete Language performed by user", userId, language.Id);
uow.Events.Dispatch(DeletedLanguage, this, new DeleteEventArgs<ILanguage>(language, false));
Audit(uow, AuditType.Delete, "Delete Language performed by user", userId, language.Id);
uow.Commit();
}
}
private void Audit(AuditType type, string message, int userId, int objectId)
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
/// <summary>
/// This is here to take care of a hack - the DictionaryTranslation model contains an ILanguage reference which we don't want but
/// This is here to take care of a hack - the DictionaryTranslation model contains an ILanguage reference which we don't want but
/// we cannot remove it because it would be a large breaking change, so we need to make sure it's resolved lazily. This is because
/// if developers have a lot of dictionary items and translations, the caching and cloning size gets much much larger because of
/// if developers have a lot of dictionary items and translations, the caching and cloning size gets much much larger because of
/// the large object graphs. So now we don't cache or clone the attached ILanguage
/// </summary>
private void EnsureDictionaryItemLanguageCallback(IDictionaryItem d)
+14 -18
View File
@@ -57,7 +57,7 @@ namespace Umbraco.Core.Services
/// <returns>An <see cref="IMacro"/> object</returns>
public IMacro GetByAlias(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMacroRepository(uow);
var q = new Query<IMacro>();
@@ -91,7 +91,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IMacro> GetAll(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMacroRepository(uow);
return repository.GetAll(ids);
@@ -100,7 +100,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IMacro> GetAll(params Guid[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMacroRepository(uow);
return repository.GetAll(ids);
@@ -109,7 +109,7 @@ namespace Umbraco.Core.Services
public IMacro GetById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMacroRepository(uow);
return repository.Get(id);
@@ -118,7 +118,7 @@ namespace Umbraco.Core.Services
public IMacro GetById(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMacroRepository(uow);
return repository.Get(id);
@@ -151,12 +151,12 @@ namespace Umbraco.Core.Services
}
var repository = RepositoryFactory.CreateMacroRepository(uow);
repository.Delete(macro);
uow.Commit();
uow.Events.Dispatch(Deleted, this, new DeleteEventArgs<IMacro>(macro, false));
}
Audit(AuditType.Delete, "Delete Macro performed by user", userId, -1);
Audit(uow, AuditType.Delete, "Delete Macro performed by user", userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -181,12 +181,12 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateMacroRepository(uow);
repository.AddOrUpdate(macro);
uow.Commit();
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMacro>(macro, false));
}
Audit(AuditType.Save, "Save Macro performed by user", userId, -1);
Audit(uow, AuditType.Save, "Save Macro performed by user", userId, -1);
uow.Commit();
}
}
///// <summary>
@@ -208,14 +208,10 @@ namespace Umbraco.Core.Services
// return MacroPropertyTypeResolver.Current.MacroPropertyTypes.FirstOrDefault(x => x.Alias == alias);
//}
private void Audit(AuditType type, string message, int userId, int objectId)
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
#region Event Handlers
+140 -164
View File
@@ -11,7 +11,6 @@ using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Media;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
@@ -28,7 +27,7 @@ namespace Umbraco.Core.Services
public class MediaService : ScopeRepositoryService, IMediaService, IMediaServiceOperations
{
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//for example, the Move method needs to be locked but this calls the Save method which also needs to be locked.
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
@@ -67,9 +66,7 @@ namespace Umbraco.Core.Services
var parent = GetById(media.ParentId);
media.Path = string.Concat(parent.IfNotNull(x => x.Path, media.ParentId.ToString()), ",", media.Id);
//we are using GetReadOnlyUnitOfWork because this actually doesn't write anything!
// fixme - IS IT EVEN DOING ANYTHING WITH REPO? NO! SO USE A SCOPE INSTEAD!
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Creating, this, new NewEventArgs<IMedia>(media, mediaTypeAlias, parentId)))
{
@@ -79,15 +76,12 @@ namespace Umbraco.Core.Services
}
media.CreatorId = userId;
uow.Events.Dispatch(Created, this, new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parentId));
Audit(AuditType.New, string.Format("Media '{0}' was created", name), media.CreatorId, media.Id);
Audit(uow, AuditType.New, string.Format("Media '{0}' was created", name), media.CreatorId, media.Id);
uow.Commit();
return media;
}
}
/// <summary>
@@ -112,9 +106,7 @@ namespace Umbraco.Core.Services
var media = new Models.Media(name, parent, mediaType);
media.Path = string.Concat(parent.Path, ",", media.Id);
//we are using GetReadOnlyUnitOfWork because this actually doesn't write anything!
// fixme
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Creating, this, new NewEventArgs<IMedia>(media, mediaTypeAlias, parent)))
{
@@ -127,7 +119,8 @@ namespace Umbraco.Core.Services
uow.Events.Dispatch(Created, this, new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parent));
Audit(AuditType.New, string.Format("Media '{0}' was created", name), media.CreatorId, media.Id);
Audit(uow, AuditType.New, string.Format("Media '{0}' was created", name), media.CreatorId, media.Id);
uow.Commit();
return media;
}
@@ -157,12 +150,14 @@ namespace Umbraco.Core.Services
// out that in these 'WithIdentity' methods, the Saving/Saved events were not fired, wtf. Anyways, they're added now.
if (uow.Events.DispatchCancelable(Creating, this, new NewEventArgs<IMedia>(media, mediaTypeAlias, parentId)))
{
uow.Commit();
media.WasCancelled = true;
return media;
}
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(media)))
{
uow.Commit();
media.WasCancelled = true;
return media;
}
@@ -170,21 +165,19 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateMediaRepository(uow);
media.CreatorId = userId;
repository.AddOrUpdate(media);
repository.AddOrUpdateContentXml(media, m => _entitySerializer.Serialize(this, _dataTypeService, _userService, m));
// generate preview for blame history?
if (UmbracoConfig.For.UmbracoSettings().Content.GlobalPreviewStorageEnabled)
{
repository.AddOrUpdatePreviewXml(media, m => _entitySerializer.Serialize(this, _dataTypeService, _userService, m));
}
uow.Commit();
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMedia>(media, false));
uow.Events.Dispatch(Created, this, new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parentId));
}
Audit(AuditType.New, string.Format("Media '{0}' was created with Id {1}", name, media.Id), media.CreatorId, media.Id);
Audit(uow, AuditType.New, string.Format("Media '{0}' was created with Id {1}", name, media.Id), media.CreatorId, media.Id);
uow.Commit();
}
return media;
}
@@ -215,17 +208,18 @@ namespace Umbraco.Core.Services
// out that in these 'WithIdentity' methods, the Saving/Saved events were not fired, wtf. Anyways, they're added now.
if (uow.Events.DispatchCancelable(Creating, this, new NewEventArgs<IMedia>(media, mediaTypeAlias, parent)))
{
uow.Commit();
media.WasCancelled = true;
return media;
}
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(media)))
{
uow.Commit();
media.WasCancelled = true;
return media;
}
var repository = RepositoryFactory.CreateMediaRepository(uow);
media.CreatorId = userId;
repository.AddOrUpdate(media);
@@ -236,13 +230,12 @@ namespace Umbraco.Core.Services
repository.AddOrUpdatePreviewXml(media, m => _entitySerializer.Serialize(this, _dataTypeService, _userService, m));
}
uow.Commit();
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMedia>(media, false));
uow.Events.Dispatch(Created, this, new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parent));
}
Audit(AuditType.New, string.Format("Media '{0}' was created with Id {1}", name, media.Id), media.CreatorId, media.Id);
Audit(uow, AuditType.New, string.Format("Media '{0}' was created with Id {1}", name, media.Id), media.CreatorId, media.Id);
uow.Commit();
}
return media;
}
@@ -254,7 +247,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMedia"/></returns>
public IMedia GetById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.Get(id);
@@ -286,7 +279,7 @@ namespace Umbraco.Core.Services
public int Count(string contentTypeAlias = null)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.Count(contentTypeAlias);
@@ -295,7 +288,7 @@ namespace Umbraco.Core.Services
public int CountChildren(int parentId, string contentTypeAlias = null)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.CountChildren(parentId, contentTypeAlias);
@@ -304,7 +297,7 @@ namespace Umbraco.Core.Services
public int CountDescendants(int parentId, string contentTypeAlias = null)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.CountDescendants(parentId, contentTypeAlias);
@@ -320,7 +313,7 @@ namespace Umbraco.Core.Services
{
if (ids.Any() == false) return Enumerable.Empty<IMedia>();
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.GetAll(ids.ToArray());
@@ -334,7 +327,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMedia"/></returns>
public IMedia GetById(Guid key)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder.Where(x => x.Key == key);
@@ -349,7 +342,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetByLevel(int level)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder.Where(x => x.Level == level && x.Path.StartsWith("-21") == false);
@@ -364,7 +357,7 @@ namespace Umbraco.Core.Services
/// <returns>An <see cref="IMedia"/> item</returns>
public IMedia GetByVersion(Guid versionId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.GetByVersion(versionId);
@@ -378,7 +371,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetVersions(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.GetAllVersions(id);
@@ -407,7 +400,7 @@ namespace Umbraco.Core.Services
if (ids.Any() == false)
return new List<IMedia>();
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.GetAll(ids);
@@ -421,7 +414,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetChildren(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder.Where(x => x.ParentId == id);
@@ -494,7 +487,7 @@ namespace Umbraco.Core.Services
Mandate.ParameterCondition(pageIndex >= 0, "pageIndex");
Mandate.ParameterCondition(pageSize > 0, "pageSize");
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
@@ -558,7 +551,7 @@ namespace Umbraco.Core.Services
{
Mandate.ParameterCondition(pageIndex >= 0, "pageIndex");
Mandate.ParameterCondition(pageSize > 0, "pageSize");
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder;
@@ -602,7 +595,7 @@ namespace Umbraco.Core.Services
if (media.ValidatePath() == false)
throw new InvalidDataException(string.Format("The content item {0} has an invalid path: {1} with parentID: {2}", media.Id, media.Path, media.ParentId));
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var pathMatch = media.Path + ",";
@@ -642,7 +635,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetMediaOfMediaType(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder.Where(x => x.ContentTypeId == id);
@@ -656,7 +649,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetRootMedia()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder.Where(x => x.ParentId == -1);
@@ -670,7 +663,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetMediaInRecycleBin()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder.Where(x => x.Path.Contains("-21"));
@@ -707,11 +700,11 @@ namespace Umbraco.Core.Services
var sql = createSql(umbracoFileValue);
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var propertyDataDto = uow.Database.Fetch<PropertyDataDto, PropertyTypeDto>(sql).FirstOrDefault();
// If the stripped-down url returns null, we try again with the original url.
// If the stripped-down url returns null, we try again with the original url.
// Previously, the function would fail on e.g. "my_x_image.jpg"
if (propertyDataDto == null)
{
@@ -754,7 +747,7 @@ namespace Umbraco.Core.Services
/// <returns>True if the media has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
var query = Query<IMedia>.Builder.Where(x => x.ParentId == id);
@@ -784,14 +777,13 @@ namespace Umbraco.Core.Services
return;
}
using (var scope = UowProvider.ScopeProvider.CreateScope())
using (var uow = UowProvider.GetUnitOfWork())
{
scope.Complete(); // always complete
var originalPath = media.Path;
if (scope.Events.DispatchCancelable(Moving, this, new MoveEventArgs<IMedia>(new MoveEventInfo<IMedia>(media, originalPath, parentId)), "Moving"))
if (uow.Events.DispatchCancelable(Moving, this, new MoveEventArgs<IMedia>(new MoveEventInfo<IMedia>(media, originalPath, parentId)), "Moving"))
{
uow.Commit();
return;
}
@@ -800,15 +792,13 @@ namespace Umbraco.Core.Services
{
media.ChangeTrashedState(false, parentId);
}
Save(media, userId,
//no events!
false);
Save(media, userId, false); //no events!
//used to track all the moved entities to be given to the event
var moveInfo = new List<MoveEventInfo<IMedia>>
{
new MoveEventInfo<IMedia>(media, originalPath, parentId)
};
{
new MoveEventInfo<IMedia>(media, originalPath, parentId)
};
//Ensure that relevant properties are updated on children
var children = GetChildren(media.Id).ToArray();
@@ -818,14 +808,13 @@ namespace Umbraco.Core.Services
var parentLevel = media.Level;
var parentTrashed = media.Trashed;
var updatedDescendants = UpdatePropertiesOnChildren(children, parentPath, parentLevel, parentTrashed, moveInfo);
Save(updatedDescendants, userId,
//no events!
false);
Save(updatedDescendants, userId, false); //no events!
}
scope.Events.Dispatch(Moved, this, new MoveEventArgs<IMedia>(false, moveInfo.ToArray()), "Moved");
uow.Events.Dispatch(Moved, this, new MoveEventArgs<IMedia>(false, moveInfo.ToArray()), "Moved");
Audit(AuditType.Move, "Move Media performed by user", userId, media.Id);
Audit(uow, AuditType.Move, "Move Media performed by user", userId, media.Id);
uow.Commit();
}
}
}
@@ -854,31 +843,35 @@ namespace Umbraco.Core.Services
//TODO: IT would be much nicer to mass delete all in one trans in the repo level!
var evtMsgs = EventMessagesFactory.Get();
using (var scope = UowProvider.ScopeProvider.CreateScope())
using (var uow = UowProvider.GetUnitOfWork())
{
scope.Complete(); // always
if (scope.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<IMedia>(media, evtMsgs)))
return OperationStatus.Cancelled(evtMsgs);
var ret = DeleteUow(uow, media, userId, evtMsgs);
uow.Commit();
return ret;
}
}
private Attempt<OperationStatus> DeleteUow(IScopeUnitOfWork uow, IMedia media, int userId, EventMessages evtMsgs)
{
if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<IMedia>(media, evtMsgs)))
{
return OperationStatus.Cancelled(evtMsgs);
}
//Delete children before deleting the 'possible parent'
// delete children first
var children = GetChildren(media.Id);
foreach (var child in children)
{
Delete(child, userId);
DeleteUow(uow, child, userId, evtMsgs);
}
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
repository.Delete(media);
uow.Commit();
var repository = RepositoryFactory.CreateMediaRepository(uow);
repository.Delete(media);
var args = new DeleteEventArgs<IMedia>(media, false, evtMsgs);
uow.Events.Dispatch(Deleted, this, args);
}
var args = new DeleteEventArgs<IMedia>(media, false, evtMsgs);
uow.Events.Dispatch(Deleted, this, args);
Audit(AuditType.Delete, "Delete Media performed by user", userId, media.Id);
Audit(uow, AuditType.Delete, "Delete Media performed by user", userId, media.Id);
return OperationStatus.Success(evtMsgs);
}
@@ -895,10 +888,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (raiseEvents)
if (raiseEvents && uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(media, evtMsgs)))
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(media, evtMsgs)))
return OperationStatus.Cancelled(evtMsgs);
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
if (string.IsNullOrWhiteSpace(media.Name))
@@ -916,13 +909,12 @@ namespace Umbraco.Core.Services
repository.AddOrUpdatePreviewXml(media, m => _entitySerializer.Serialize(this, _dataTypeService, _userService, m));
}
uow.Commit();
if (raiseEvents)
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMedia>(media, false, evtMsgs));
}
Audit(AuditType.Save, "Save Media performed by user", userId, media.Id);
Audit(uow, AuditType.Save, "Save Media performed by user", userId, media.Id);
uow.Commit();
}
return OperationStatus.Success(evtMsgs);
}
@@ -940,10 +932,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (raiseEvents)
if (raiseEvents && uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(asArray, evtMsgs)))
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(asArray, evtMsgs)))
return OperationStatus.Cancelled(evtMsgs);
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
var repository = RepositoryFactory.CreateMediaRepository(uow);
@@ -959,14 +951,12 @@ namespace Umbraco.Core.Services
}
}
//commit the whole lot in one go
uow.Commit();
if (raiseEvents)
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMedia>(asArray, false, evtMsgs));
}
Audit(AuditType.Save, "Save Media items performed by user", userId, -1);
Audit(uow, AuditType.Save, "Save Media items performed by user", userId, -1);
uow.Commit();
}
return OperationStatus.Success(evtMsgs);
}
@@ -978,18 +968,14 @@ namespace Umbraco.Core.Services
{
using (new WriteLock(Locker))
{
Dictionary<int, IEnumerable<Property>> entities;
List<string> files;
bool success;
var nodeObjectType = new Guid(Constants.ObjectTypes.Media);
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
entities = repository.GetEntitiesInRecycleBin().ToDictionary(key => key.Id, val => (IEnumerable<Property>)val.Properties);
var entities = repository.GetEntitiesInRecycleBin().ToDictionary(key => key.Id, val => (IEnumerable<Property>)val.Properties);
files = ((MediaRepository)repository).GetFilesInRecycleBinForUploadField();
uow.Commit();
var files = ((MediaRepository)repository).GetFilesInRecycleBinForUploadField();
if (uow.Events.DispatchCancelable(EmptyingRecycleBin, this, new RecycleBinEventArgs(nodeObjectType, entities, files)))
{
@@ -997,17 +983,19 @@ namespace Umbraco.Core.Services
return;
}
success = repository.EmptyRecycleBin();
// FIXME shouldn't we commit here?!
var success = repository.EmptyRecycleBin();
uow.Events.Dispatch(EmptiedRecycleBin, this, new RecycleBinEventArgs(nodeObjectType, entities, files, success));
Audit(uow, AuditType.Delete, "Empty Media Recycle Bin performed by user", 0, -21);
uow.Commit();
}
}
Audit(AuditType.Delete, "Empty Media Recycle Bin performed by user", 0, -21);
}
/// <summary>
/// Deletes all content of the specified types. All Descendants of deleted content that is not of these types is moved to Recycle Bin.
/// </summary>
/// </summary>
/// <param name="mediaTypeIds">Id of the <see cref="IContentType"/></param>
/// <param name="userId">Optional Id of the user issueing the delete operation</param>
public void DeleteMediaOfTypes(IEnumerable<int> mediaTypeIds, int userId = 0)
@@ -1032,12 +1020,8 @@ namespace Umbraco.Core.Services
//Determine the items that will need to be recycled (that are children of these content items but not of these content types)
var mediaToRecycle = this.TrackTrashedForDeleteContentOfTypes(mediaTypeIds, rootItems, repository);
// do it INSIDE the UOW because nested UOW kinda should work
// fixme - and then we probably don't need the whole mess?
// nesting UOW works, it's just that the outer one NEEDS to be flushed beforehand
// nevertheless, it would be nicer to create a global scope and inner uow
//move each item to the bin starting with the deepest items
// move each item to the bin starting with the deepest items
// nesting uow - technically supported though not ideal
foreach (var child in mediaToRecycle.OrderByDescending(x => x.Level))
{
MoveToRecycleBinDo(child, userId, true);
@@ -1048,12 +1032,10 @@ namespace Umbraco.Core.Services
Delete(content, userId);
}
uow.Commit();
Audit(AuditType.Delete,
Audit(uow, AuditType.Delete,
string.Format("Delete Media of Types {0} performed by user", string.Join(",", mediaTypeIds)),
userId, Constants.System.Root);
uow.Commit();
}
}
@@ -1105,13 +1087,13 @@ namespace Umbraco.Core.Services
{
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
}
var moveInfo = new List<MoveEventInfo<IMedia>>
{
new MoveEventInfo<IMedia>(media, originalPath, Constants.System.RecycleBinMedia)
};
//get descendents to process of the content item that is being moved to trash - must be done before changing the state below,
//get descendents to process of the content item that is being moved to trash - must be done before changing the state below,
//must be processed with shallowest levels first
var descendants = ignoreDescendants ? Enumerable.Empty<IMedia>() : GetDescendants(media).OrderBy(x => x.Level);
@@ -1120,7 +1102,7 @@ namespace Umbraco.Core.Services
repository.DeleteContentXml(media);
media.ChangeTrashedState(true, Constants.System.RecycleBinMedia);
repository.AddOrUpdate(media);
//Loop through descendants to update their trash state, but ensuring structure by keeping the ParentId
foreach (var descendant in descendants)
{
@@ -1131,12 +1113,11 @@ namespace Umbraco.Core.Services
moveInfo.Add(new MoveEventInfo<IMedia>(descendant, descendant.Path, descendant.ParentId));
}
uow.Commit();
uow.Events.Dispatch(Trashed, this, new MoveEventArgs<IMedia>(false, evtMsgs, moveInfo.ToArray()), "Trashed");
}
Audit(AuditType.Move, "Move Media to Recycle Bin performed by user", userId, media.Id);
Audit(uow, AuditType.Move, "Move Media to Recycle Bin performed by user", userId, media.Id);
uow.Commit();
}
return OperationStatus.Success(evtMsgs);
}
@@ -1166,19 +1147,22 @@ namespace Umbraco.Core.Services
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
public void DeleteVersions(int id, DateTime versionDate, int userId = 0)
{
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(DeletingVersions, this, new DeleteRevisionsEventArgs(id, dateToRetain: versionDate)))
return;
var repository = RepositoryFactory.CreateMediaRepository(uow);
repository.DeleteVersions(id, versionDate);
DeleteVersions(uow, id, versionDate, userId);
uow.Commit();
uow.Events.Dispatch(DeletedVersions, this, new DeleteRevisionsEventArgs(id, false, dateToRetain: versionDate));
}
}
Audit(AuditType.Delete, "Delete Media by version date performed by user", userId, -1);
private void DeleteVersions(IScopeUnitOfWork uow, int id, DateTime versionDate, int userId = 0)
{
if (uow.Events.DispatchCancelable(DeletingVersions, this, new DeleteRevisionsEventArgs(id, dateToRetain: versionDate)))
return;
var repository = RepositoryFactory.CreateMediaRepository(uow);
repository.DeleteVersions(id, versionDate);
uow.Events.Dispatch(DeletedVersions, this, new DeleteRevisionsEventArgs(id, false, dateToRetain: versionDate));
Audit(uow, AuditType.Delete, "Delete Media by version date performed by user", userId, -1);
}
/// <summary>
@@ -1191,28 +1175,28 @@ namespace Umbraco.Core.Services
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
public void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0)
{
using (var scope = UowProvider.ScopeProvider.CreateScope())
{
scope.Complete(); // always
if (scope.Events.DispatchCancelable(DeletingVersions, this, new DeleteRevisionsEventArgs(id, specificVersion: versionId)))
return;
}
if (deletePriorVersions)
{
var content = GetByVersion(versionId);
DeleteVersions(id, content.UpdateDate, userId);
}
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(DeletingVersions, this, new DeleteRevisionsEventArgs(id, specificVersion: versionId)))
{
uow.Commit();
return;
}
if (deletePriorVersions)
{
var content = GetByVersion(versionId);
DeleteVersions(uow, id, content.UpdateDate, userId);
}
var repository = RepositoryFactory.CreateMediaRepository(uow);
repository.DeleteVersion(versionId);
uow.Commit();
uow.Events.Dispatch(DeletedVersions, this, new DeleteRevisionsEventArgs(id, false, specificVersion: versionId));
}
Audit(AuditType.Delete, "Delete Media by version performed by user", userId, -1);
uow.Events.Dispatch(DeletedVersions, this, new DeleteRevisionsEventArgs(id, false, specificVersion: versionId));
Audit(uow, AuditType.Delete, "Delete Media by version performed by user", userId, -1);
uow.Commit();
}
}
/// <summary>
@@ -1251,13 +1235,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (raiseEvents)
if (raiseEvents && uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(asArray)))
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMedia>(asArray)))
{
uow.Commit();
return false;
}
uow.Commit();
return false;
}
var repository = RepositoryFactory.CreateMediaRepository(uow);
@@ -1285,13 +1266,12 @@ namespace Umbraco.Core.Services
}
}
uow.Commit();
if (raiseEvents)
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMedia>(asArray, false));
}
Audit(AuditType.Sort, "Sorting Media performed by user", userId, 0);
Audit(uow, AuditType.Sort, "Sorting Media performed by user", userId, 0);
uow.Commit();
}
return true;
}
@@ -1309,7 +1289,7 @@ namespace Umbraco.Core.Services
Mandate.ParameterCondition(pageIndex >= 0, "pageIndex");
Mandate.ParameterCondition(pageSize > 0, "pageSize");
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
return repository.GetPagedXmlEntriesByPath(path, pageIndex, pageSize, null, out totalRecords);
@@ -1329,10 +1309,10 @@ namespace Umbraco.Core.Services
{
var repository = RepositoryFactory.CreateMediaRepository(uow);
repository.RebuildXmlStructures(media => _entitySerializer.Serialize(this, _dataTypeService, _userService, media), contentTypeIds: contentTypeIds.Length == 0 ? null : contentTypeIds);
Audit(uow, AuditType.Publish, "MediaService.RebuildXmlStructures completed, the xml has been regenerated in the database", 0, -1);
uow.Commit();
}
Audit(AuditType.Publish, "MediaService.RebuildXmlStructures completed, the xml has been regenerated in the database", 0, -1);
}
/// <summary>
@@ -1381,7 +1361,7 @@ namespace Umbraco.Core.Services
{
Mandate.ParameterNotNullOrEmpty(mediaTypeAlias, "mediaTypeAlias");
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMediaTypeRepository(uow);
var query = Query<IMediaType>.Builder.Where(x => x.Alias == mediaTypeAlias);
@@ -1399,14 +1379,10 @@ namespace Umbraco.Core.Services
}
}
private void Audit(AuditType type, string message, int userId, int objectId)
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
/// <summary>
@@ -1468,7 +1444,7 @@ namespace Umbraco.Core.Services
/// <summary>
/// Occurs before Delete
/// </summary>
/// </summary>
public static event TypedEventHandler<IMediaService, DeleteRevisionsEventArgs> DeletingVersions;
/// <summary>
+13 -16
View File
@@ -1,11 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
@@ -40,12 +37,12 @@ namespace Umbraco.Core.Services
scope.Complete(); // always complete
scope.Events.Dispatch(Saved, this, new SaveEventArgs<IMemberGroup>(e.SavedEntities, false));
}
}
}
#endregion
public IEnumerable<IMemberGroup> GetAll()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
return repository.GetAll();
@@ -54,7 +51,7 @@ namespace Umbraco.Core.Services
public IMemberGroup GetById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
return repository.Get(id);
@@ -63,7 +60,7 @@ namespace Umbraco.Core.Services
public IMemberGroup GetByName(string name)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
return repository.GetByName(name);
@@ -74,13 +71,10 @@ namespace Umbraco.Core.Services
{
using (var uow = UowProvider.GetUnitOfWork())
{
if (raiseEvents)
if (raiseEvents && uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMemberGroup>(memberGroup)))
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMemberGroup>(memberGroup)))
{
uow.Commit();
return;
}
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
@@ -90,7 +84,7 @@ namespace Umbraco.Core.Services
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMemberGroup>(memberGroup, false));
}
}
public void Delete(IMemberGroup memberGroup)
@@ -98,7 +92,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<IMemberGroup>(memberGroup)))
return; // FIXME COMMIT
{
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
repository.Delete(memberGroup);
uow.Commit();
@@ -118,7 +115,7 @@ namespace Umbraco.Core.Services
/// <summary>
/// Occurs before Save of a member group
/// </summary>
/// </summary>
/// <remarks>
/// We need to proxy these events because the events need to take place at the repo level
/// </remarks>
+61 -67
View File
@@ -4,17 +4,14 @@ using System.ComponentModel;
using System.Threading;
using System.Web.Security;
using System.Xml.Linq;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using System.Linq;
using Umbraco.Core.Security;
@@ -50,7 +47,7 @@ namespace Umbraco.Core.Services
/// <returns>Alias of the default MemberType</returns>
public string GetDefaultMemberType()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberTypeRepository(uow);
@@ -76,7 +73,7 @@ namespace Umbraco.Core.Services
/// <returns><c>True</c> if the Member exists otherwise <c>False</c></returns>
public bool Exists(string username)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.Exists(username);
@@ -123,7 +120,7 @@ namespace Umbraco.Core.Services
/// <returns><c>True</c> if the Member exists otherwise <c>False</c></returns>
public bool Exists(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.Exists(id);
@@ -137,7 +134,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMember"/></returns>
public IMember GetById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.Get(id);
@@ -153,7 +150,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMember"/></returns>
public IMember GetByKey(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
var query = Query<IMember>.Builder.Where(x => x.Key == id);
@@ -168,7 +165,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetMembersByMemberType(string memberTypeAlias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
var query = Query<IMember>.Builder.Where(x => x.ContentTypeAlias == memberTypeAlias);
@@ -183,7 +180,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetMembersByMemberType(int memberTypeId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
repository.Get(memberTypeId);
@@ -199,7 +196,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetMembersByGroup(string memberGroupName)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.GetByMemberGroup(memberGroupName);
@@ -214,7 +211,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetAllMembers(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.GetAll(ids);
@@ -229,8 +226,6 @@ namespace Umbraco.Core.Services
{
using (new WriteLock(Locker))
{
var memberList = new List<IMember>();
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
@@ -246,9 +241,8 @@ namespace Umbraco.Core.Services
}
foreach (var member in members)
{
//Permantly delete the member
// FIXME implies a nested UOW = bad so ?
Delete(member);
// permantly delete the member
Delete(uow, member);
}
uow.Commit();
@@ -277,7 +271,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> FindMembersByDisplayName(string displayNameToMatch, long pageIndex, int pageSize, out long totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
var query = new Query<IMember>();
@@ -328,7 +322,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> FindByEmail(string emailStringToMatch, long pageIndex, int pageSize, out long totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
var query = new Query<IMember>();
@@ -379,7 +373,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> FindByUsername(string login, long pageIndex, int pageSize, out long totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
var query = new Query<IMember>();
@@ -418,7 +412,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, string value, StringPropertyMatchType matchType = StringPropertyMatchType.Exact)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
@@ -467,7 +461,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, int value, ValuePropertyMatchType matchType = ValuePropertyMatchType.Exact)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
@@ -506,7 +500,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, bool value)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
@@ -524,7 +518,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, DateTime value, ValuePropertyMatchType matchType = ValuePropertyMatchType.Exact)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
@@ -572,10 +566,10 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateMemberRepository(uow);
repository.RebuildXmlStructures(member => _entitySerializer.Serialize(_dataTypeService, member),
contentTypeIds: memberTypeIds.Length == 0 ? null : memberTypeIds);
Audit(uow, AuditType.Publish, "MemberService.RebuildXmlStructures completed, the xml has been regenerated in the database", 0, -1);
uow.Commit();
}
Audit(AuditType.Publish, "MemberService.RebuildXmlStructures completed, the xml has been regenerated in the database", 0, -1);
}
/// <summary>
@@ -590,11 +584,10 @@ namespace Umbraco.Core.Services
Mandate.ParameterCondition(pageIndex >= 0, "pageIndex");
Mandate.ParameterCondition(pageSize > 0, "pageSize");
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMemberRepository(uow))
using (var uow = UowProvider.GetUnitOfWork(readOnly:true))
{
var contents = repository.GetPagedXmlEntriesByPath("-1", pageIndex, pageSize, null, out totalRecords);
return contents;
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.GetPagedXmlEntriesByPath("-1", pageIndex, pageSize, null, out totalRecords);
}
}
@@ -614,7 +607,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="System.int"/> with number of Members for passed in type</returns>
public int GetCount(MemberCountType countType)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
@@ -666,7 +659,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IMember> GetAll(long pageIndex, int pageSize, out long totalRecords)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.GetPagedResultsByQuery(null, pageIndex, pageSize, out totalRecords, "LoginName", Direction.Ascending, true);
@@ -693,7 +686,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IMember> GetAll(long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string memberTypeAlias, string filter)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
IQuery<IMember> filterQuery = null;
if (filter.IsNullOrWhiteSpace() == false)
@@ -725,7 +718,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="System.int"/> with number of Members</returns>
public int Count(string memberTypeAlias = null)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.Count(memberTypeAlias);
@@ -906,7 +899,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMember"/></returns>
public IMember GetByEmail(string email)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
var query = Query<IMember>.Builder.Where(x => x.Email.Equals(email));
@@ -925,7 +918,7 @@ namespace Umbraco.Core.Services
// a caching mechanism since this method is used by all the membership providers and could be
// called quite a bit when dealing with members.
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
var query = Query<IMember>.Builder.Where(x => x.Username.Equals(username));
@@ -941,21 +934,27 @@ namespace Umbraco.Core.Services
{
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<IMember>(member)))
{
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateMemberRepository(uow);
repository.Delete(member);
Delete(uow, member);
uow.Commit();
var args = new DeleteEventArgs<IMember>(member, false);
uow.Events.Dispatch(Deleted, this, args);
}
}
private void Delete(IScopeUnitOfWork uow, IMember member)
{
if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<IMember>(member)))
{
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateMemberRepository(uow);
repository.Delete(member);
uow.Commit();
var args = new DeleteEventArgs<IMember>(member, false);
uow.Events.Dispatch(Deleted, this, args);
}
/// <summary>
/// Saves an <see cref="IMember"/>
/// </summary>
@@ -1011,14 +1010,12 @@ namespace Umbraco.Core.Services
{
using (var uow = UowProvider.GetUnitOfWork())
{
if (raiseEvents)
if (raiseEvents && uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMember>(asArray)))
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<IMember>(asArray)))
{
uow.Commit();
return;
}
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateMemberRepository(uow);
foreach (var member in asArray)
{
@@ -1058,7 +1055,7 @@ namespace Umbraco.Core.Services
public IEnumerable<string> GetAllRoles()
{
using (var uow = UowProvider.GetUnitOfWork())
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
var result = repository.GetAll();
@@ -1068,7 +1065,7 @@ namespace Umbraco.Core.Services
public IEnumerable<string> GetAllRoles(int memberId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
var result = repository.GetMemberGroupsForMember(memberId);
@@ -1078,7 +1075,7 @@ namespace Umbraco.Core.Services
public IEnumerable<string> GetAllRoles(string username)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
var result = repository.GetMemberGroupsForMember(username);
@@ -1088,7 +1085,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IMember> GetMembersInRole(string roleName)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.GetByMemberGroup(roleName);
@@ -1097,7 +1094,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IMember> FindMembersInRole(string roleName, string usernameToMatch, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberRepository(uow);
return repository.FindMembersInRole(roleName, usernameToMatch, matchType);
@@ -1119,7 +1116,7 @@ namespace Umbraco.Core.Services
List<IMemberGroup> found;
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberGroupRepository(uow);
var qry = new Query<IMemberGroup>().Where(g => g.Name == roleName);
@@ -1199,7 +1196,7 @@ namespace Umbraco.Core.Services
private IMemberType FindMemberTypeByAlias(string memberTypeAlias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateMemberTypeRepository(uow);
var query = Query<IMemberType>.Builder.Where(x => x.Alias == memberTypeAlias);
@@ -1213,19 +1210,16 @@ namespace Umbraco.Core.Services
if (contentType == null)
throw new Exception(string.Format("MemberType matching the passed in Alias: '{0}' was null", memberTypeAlias));
uow.Commit();
return contentType;
}
}
private void Audit(AuditType type, string message, int userId, int objectId)
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
var repository = RepositoryFactory.CreateAuditRepository(uow);
repository.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
#region Event Handlers
+8 -14
View File
@@ -2,12 +2,10 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Umbraco.Core.Auditing;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
@@ -18,7 +16,6 @@ namespace Umbraco.Core.Services
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
public MemberTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IMemberService memberService)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
@@ -28,7 +25,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IMemberType> GetAll(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberTypeRepository(uow);
return repository.GetAll(ids);
@@ -42,7 +39,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMemberType"/></returns>
public IMemberType Get(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberTypeRepository(uow);
return repository.Get(id);
@@ -56,7 +53,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMemberType"/></returns>
public IMemberType Get(Guid key)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberTypeRepository(uow);
return repository.Get(key);
@@ -70,7 +67,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IMemberType"/></returns>
public IMemberType Get(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateMemberTypeRepository(uow);
return repository.Get(alias);
@@ -97,10 +94,10 @@ namespace Umbraco.Core.Services
var repository = RepositoryFactory.CreateMemberTypeRepository(uow);
memberType.CreatorId = userId;
repository.AddOrUpdate(memberType);
uow.Commit(); // flush, so that the db contains the saved value
uow.Commit(); // fixme double?
UpdateContentXmlStructure(memberType);
uow.Commit();
uow.Commit(); // actually commit uow
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMemberType>(memberType, false));
}
@@ -126,13 +123,10 @@ namespace Umbraco.Core.Services
memberType.CreatorId = userId;
repository.AddOrUpdate(memberType);
}
uow.Commit(); // fixme double?
uow.Commit(); // flush, so that the db contains the saved values
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
//save it all in one go
uow.Commit();
uow.Commit(); // actually commit uow
uow.Events.Dispatch(Saved, this, new SaveEventArgs<IMemberType>(asArray, false));
}
@@ -24,7 +24,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<PublicAccessEntry> GetAll()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreatePublicAccessRepository(uow);
return repo.GetAll();
@@ -69,7 +69,7 @@ namespace Umbraco.Core.Services
//start with the deepest id
ids.Reverse();
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
//This will retrieve from cache!
var repo = RepositoryFactory.CreatePublicAccessRepository(uow);
@@ -220,7 +220,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Saving, this, new SaveEventArgs<PublicAccessEntry>(entry, evtMsgs)))
{
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
var repo = RepositoryFactory.CreatePublicAccessRepository(uow);
repo.AddOrUpdate(entry);
@@ -243,7 +246,10 @@ namespace Umbraco.Core.Services
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs<PublicAccessEntry>(entry, evtMsgs)))
{
uow.Commit();
return OperationStatus.Cancelled(evtMsgs);
}
var repo = RepositoryFactory.CreatePublicAccessRepository(uow);
repo.Delete(entry);
+19 -33
View File
@@ -29,7 +29,7 @@ namespace Umbraco.Core.Services
/// <returns>A <see cref="Relation"/> object</returns>
public IRelation GetById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
return repository.Get(id);
@@ -43,7 +43,7 @@ namespace Umbraco.Core.Services
/// <returns>A <see cref="RelationType"/> object</returns>
public IRelationType GetRelationTypeById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationTypeRepository(uow);
return repository.Get(id);
@@ -57,7 +57,7 @@ namespace Umbraco.Core.Services
/// <returns>A <see cref="RelationType"/> object</returns>
public IRelationType GetRelationTypeById(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationTypeRepository(uow);
return repository.Get(id);
@@ -71,7 +71,7 @@ namespace Umbraco.Core.Services
/// <returns>A <see cref="RelationType"/> object</returns>
public IRelationType GetRelationTypeByAlias(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationTypeRepository(uow);
var query = new Query<IRelationType>().Where(x => x.Alias == alias);
@@ -86,7 +86,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Relation"/> objects</returns>
public IEnumerable<IRelation> GetAllRelations(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
return repository.GetAll(ids);
@@ -110,7 +110,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Relation"/> objects</returns>
public IEnumerable<IRelation> GetAllRelationsByRelationType(int relationTypeId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.RelationTypeId == relationTypeId);
@@ -125,7 +125,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="RelationType"/> objects</returns>
public IEnumerable<IRelationType> GetAllRelationTypes(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationTypeRepository(uow);
return repository.GetAll(ids);
@@ -139,7 +139,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Relation"/> objects</returns>
public IEnumerable<IRelation> GetByParentId(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.ParentId == id);
@@ -175,7 +175,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Relation"/> objects</returns>
public IEnumerable<IRelation> GetByChildId(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.ChildId == id);
@@ -212,7 +212,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Relation"/> objects</returns>
public IEnumerable<IRelation> GetByParentOrChildId(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.ParentId == id || x.ChildId == id);
@@ -222,7 +222,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IRelation> GetByParentOrChildId(int id, string relationTypeAlias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var typeRepository = RepositoryFactory.CreateRelationTypeRepository(uow);
var rtQuery = new Query<IRelationType>().Where(x => x.Alias == relationTypeAlias);
@@ -243,7 +243,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IRelation> GetByRelationTypeName(string relationTypeName)
{
List<int> relationTypeIds = null;
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationTypeRepository(uow);
var query = new Query<IRelationType>().Where(x => x.Name == relationTypeName);
@@ -268,7 +268,7 @@ namespace Umbraco.Core.Services
public IEnumerable<IRelation> GetByRelationTypeAlias(string relationTypeAlias)
{
List<int> relationTypeIds = null;
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationTypeRepository(uow);
var query = new Query<IRelationType>().Where(x => x.Alias == relationTypeAlias);
@@ -292,7 +292,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="Relation"/> objects</returns>
public IEnumerable<IRelation> GetByRelationTypeId(int relationTypeId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.RelationTypeId == relationTypeId);
@@ -423,8 +423,6 @@ namespace Umbraco.Core.Services
uow.Events.Dispatch(SavedRelation, this, new SaveEventArgs<IRelation>(relation, false));
return relation;
}
}
/// <summary>
@@ -456,8 +454,6 @@ namespace Umbraco.Core.Services
uow.Events.Dispatch(SavedRelation, this, new SaveEventArgs<IRelation>(relation, false));
return relation;
}
}
/// <summary>
@@ -467,7 +463,7 @@ namespace Umbraco.Core.Services
/// <returns>Returns <c>True</c> if any relations exists for the given <see cref="RelationType"/>, otherwise <c>False</c></returns>
public bool HasRelations(IRelationType relationType)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.RelationTypeId == relationType.Id);
@@ -482,7 +478,7 @@ namespace Umbraco.Core.Services
/// <returns>Returns <c>True</c> if any relations exists with the given Id, otherwise <c>False</c></returns>
public bool IsRelated(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.ParentId == id || x.ChildId == id);
@@ -498,7 +494,7 @@ namespace Umbraco.Core.Services
/// <returns>Returns <c>True</c> if any relations exists with the given Ids, otherwise <c>False</c></returns>
public bool AreRelated(int parentId, int childId)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.ParentId == parentId && x.ChildId == childId);
@@ -532,7 +528,7 @@ namespace Umbraco.Core.Services
/// <returns>Returns <c>True</c> if any relations exists with the given Ids and relation type, otherwise <c>False</c></returns>
public bool AreRelated(int parentId, int childId, IRelationType relationType)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
var query = new Query<IRelation>().Where(x => x.ParentId == parentId && x.ChildId == childId && x.RelationTypeId == relationType.Id);
@@ -582,8 +578,6 @@ namespace Umbraco.Core.Services
uow.Commit();
uow.Events.Dispatch(SavedRelation, this, new SaveEventArgs<IRelation>(relation, false));
}
}
/// <summary>
@@ -604,8 +598,6 @@ namespace Umbraco.Core.Services
uow.Commit();
uow.Events.Dispatch(SavedRelationType, this, new SaveEventArgs<IRelationType>(relationType, false));
}
}
/// <summary>
@@ -625,9 +617,7 @@ namespace Umbraco.Core.Services
repository.Delete(relation);
uow.Commit();
uow.Events.Dispatch(DeletedRelation, this, new DeleteEventArgs<IRelation>(relation, false));
}
}
/// <summary>
@@ -647,9 +637,7 @@ namespace Umbraco.Core.Services
repository.Delete(relationType);
uow.Commit();
uow.Events.Dispatch(DeletedRelationType, this, new DeleteEventArgs<IRelationType>(relationType, false));
}
}
/// <summary>
@@ -671,16 +659,14 @@ namespace Umbraco.Core.Services
}
uow.Commit();
uow.Events.Dispatch(DeletedRelation, this, new DeleteEventArgs<IRelation>(relations, false));
}
}
#region Private Methods
private IEnumerable<IRelation> GetRelationsByListOfTypeIds(IEnumerable<int> relationTypeIds)
{
var relations = new List<IRelation>();
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateRelationRepository(uow);
foreach (var relationTypeId in relationTypeIds)
+2 -4
View File
@@ -2,13 +2,11 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using Umbraco.Core.Cache;
using Umbraco.Core.Events;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using File = System.IO.File;
@@ -19,7 +17,7 @@ namespace Umbraco.Core.Services
private readonly IUserService _userService;
private IEnumerable<Section> _allAvailableSections;
private readonly IApplicationTreeService _applicationTreeService;
private readonly IDatabaseUnitOfWorkProvider _uowProvider;
private readonly IScopeUnitOfWorkProvider _uowProvider;
private readonly CacheHelper _cache;
internal const string AppConfigFileName = "applications.config";
private static string _appConfig;
@@ -29,7 +27,7 @@ namespace Umbraco.Core.Services
public SectionService(
IUserService userService,
IApplicationTreeService applicationTreeService,
IDatabaseUnitOfWorkProvider uowProvider,
IScopeUnitOfWorkProvider uowProvider,
CacheHelper cache)
{
if (applicationTreeService == null) throw new ArgumentNullException("applicationTreeService");
+16 -41
View File
@@ -1,12 +1,10 @@
using System;
using System.ComponentModel;
using Umbraco.Core.Logging;
using System.IO;
using System.Linq;
using Umbraco.Core.IO;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
using Umbraco.Core.Events;
namespace Umbraco.Core.Services
@@ -15,7 +13,7 @@ namespace Umbraco.Core.Services
/// These are used currently to return the temporary 'operation' interfaces for services
/// which are used to return a status from operational methods so we can determine if things are
/// cancelled, etc...
///
///
/// These will be obsoleted in v8 since all real services methods will be changed to have the correct result.
/// </summary>
public static class ServiceWithResultExtensions
@@ -37,11 +35,11 @@ namespace Umbraco.Core.Services
/// </summary>
public class ServiceContext
{
private Lazy<IMigrationEntryService> _migrationEntryService;
private Lazy<IPublicAccessService> _publicAccessService;
private Lazy<ITaskService> _taskService;
private Lazy<IDomainService> _domainService;
private Lazy<IAuditService> _auditService;
private Lazy<IMigrationEntryService> _migrationEntryService;
private Lazy<IPublicAccessService> _publicAccessService;
private Lazy<ITaskService> _taskService;
private Lazy<IDomainService> _domainService;
private Lazy<IAuditService> _auditService;
private Lazy<ILocalizedTextService> _localizedTextService;
private Lazy<ITagService> _tagService;
private Lazy<IContentService> _contentService;
@@ -150,49 +148,30 @@ namespace Umbraco.Core.Services
if (redirectUrlService != null) _redirectUrlService = new Lazy<IRedirectUrlService>(() => redirectUrlService);
}
// fixme - but this is obsoleting a new method?!!?!!?
[Obsolete("The IPublishingStrategy parameter is no longer required and not used")]
[EditorBrowsable(EditorBrowsableState.Never)]
public ServiceContext(
RepositoryFactory repositoryFactory,
IScopeUnitOfWorkProvider dbUnitOfWorkProvider,
IScopeUnitOfWorkProvider fileUnitOfWorkProvider,
IPublishingStrategy publishingStrategy,
CacheHelper cache,
ILogger logger,
IEventMessagesFactory eventMessagesFactory)
: this(repositoryFactory, dbUnitOfWorkProvider, fileUnitOfWorkProvider, cache, logger, eventMessagesFactory)
{ }
// fixme CLEAN THIS
/// <summary>
/// Creates a service context with a RepositoryFactory which is used to construct Services
/// </summary>
/// <param name="repositoryFactory"></param>
/// <param name="dbUnitOfWorkProvider"></param>
/// <param name="fileUnitOfWorkProvider"></param>
/// <param name="provider"></param>
/// <param name="cache"></param>
/// <param name="logger"></param>
/// <param name="eventMessagesFactory"></param>
public ServiceContext(
RepositoryFactory repositoryFactory,
IScopeUnitOfWorkProvider dbUnitOfWorkProvider,
IScopeUnitOfWorkProvider fileUnitOfWorkProvider,
CacheHelper cache,
IScopeUnitOfWorkProvider provider,
CacheHelper cache,
ILogger logger,
IEventMessagesFactory eventMessagesFactory)
{
if (repositoryFactory == null) throw new ArgumentNullException("repositoryFactory");
if (dbUnitOfWorkProvider == null) throw new ArgumentNullException("dbUnitOfWorkProvider");
if (fileUnitOfWorkProvider == null) throw new ArgumentNullException("fileUnitOfWorkProvider");
if (provider == null) throw new ArgumentNullException("provider");
if (cache == null) throw new ArgumentNullException("cache");
if (logger == null) throw new ArgumentNullException("logger");
if (eventMessagesFactory == null) throw new ArgumentNullException("eventMessagesFactory");
EventMessagesFactory = eventMessagesFactory;
BuildServiceCache(dbUnitOfWorkProvider, fileUnitOfWorkProvider, cache,
BuildServiceCache(provider, cache,
repositoryFactory,
logger, eventMessagesFactory);
}
@@ -201,8 +180,7 @@ namespace Umbraco.Core.Services
/// Builds the various services
/// </summary>
private void BuildServiceCache(
IScopeUnitOfWorkProvider dbUnitOfWorkProvider,
IScopeUnitOfWorkProvider fileUnitOfWorkProvider,
IScopeUnitOfWorkProvider provider,
CacheHelper cache,
RepositoryFactory repositoryFactory,
ILogger logger,
@@ -210,9 +188,6 @@ namespace Umbraco.Core.Services
{
EventMessagesFactory = eventMessagesFactory;
var provider = dbUnitOfWorkProvider;
var fileProvider = fileUnitOfWorkProvider;
if (_migrationEntryService == null)
_migrationEntryService = new Lazy<IMigrationEntryService>(() => new MigrationEntryService(provider, repositoryFactory, logger, eventMessagesFactory));
@@ -233,7 +208,7 @@ namespace Umbraco.Core.Services
if (_localizedTextService == null)
{
_localizedTextService = new Lazy<ILocalizedTextService>(() => new LocalizedTextService(
new Lazy<LocalizedTextServiceFileSources>(() =>
{
@@ -266,7 +241,7 @@ namespace Umbraco.Core.Services
}),
logger));
}
if (_notificationService == null)
_notificationService = new Lazy<INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value, logger));
@@ -293,7 +268,7 @@ namespace Umbraco.Core.Services
_dataTypeService = new Lazy<IDataTypeService>(() => new DataTypeService(provider, repositoryFactory, logger, eventMessagesFactory));
if (_fileService == null)
_fileService = new Lazy<IFileService>(() => new FileService(fileProvider, provider, repositoryFactory, logger, eventMessagesFactory));
_fileService = new Lazy<IFileService>(() => new FileService(provider, repositoryFactory, logger, eventMessagesFactory));
if (_localizationService == null)
_localizationService = new Lazy<ILocalizationService>(() => new LocalizationService(provider, repositoryFactory, logger, eventMessagesFactory));
@@ -304,7 +279,7 @@ namespace Umbraco.Core.Services
_contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value, _memberService.Value, _memberTypeService.Value,
//TODO: Consider making this an isolated cache instead of using the global one
cache.RuntimeCache));
if (_packagingService == null)
_packagingService = new Lazy<IPackagingService>(() => new PackagingService(logger, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, _entityService.Value, _userService.Value, repositoryFactory, provider));
+39 -48
View File
@@ -1,8 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
@@ -38,12 +36,12 @@ namespace Umbraco.Core.Services
/// <summary>
/// Gets the default MemberType alias
/// </summary>
/// <remarks>By default we'll return the 'writer', but we need to check it exists. If it doesn't we'll
/// <remarks>By default we'll return the 'writer', but we need to check it exists. If it doesn't we'll
/// return the first type that is not an admin, otherwise if there's only one we will return that one.</remarks>
/// <returns>Alias of the default MemberType</returns>
public string GetDefaultMemberType()
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserTypeRepository(uow);
@@ -76,7 +74,7 @@ namespace Umbraco.Core.Services
/// <returns><c>True</c> if the User exists otherwise <c>False</c></returns>
public bool Exists(string username)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
return repository.Exists(username);
@@ -118,7 +116,7 @@ namespace Umbraco.Core.Services
/// <summary>
/// Creates and persists a Member
/// </summary>
/// <remarks>Using this method will persist the Member object before its returned
/// <remarks>Using this method will persist the Member object before its returned
/// meaning that it will have an Id available (unlike the CreateMember method)</remarks>
/// <param name="username">Username of the Member to create</param>
/// <param name="email">Email of the Member to create</param>
@@ -182,7 +180,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IUser"/></returns>
public IUser GetById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
return repository.Get(id);
@@ -212,7 +210,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IUser"/></returns>
public IUser GetByEmail(string email)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
var query = Query<IUser>.Builder.Where(x => x.Email.Equals(email));
@@ -227,7 +225,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IUser"/></returns>
public IUser GetByUsername(string username)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
var query = Query<IUser>.Builder.Where(x => x.Username.Equals(username));
@@ -305,9 +303,7 @@ namespace Umbraco.Core.Services
repository.Delete(user);
uow.Commit();
uow.Events.Dispatch(DeletedUser, this, new DeleteEventArgs<IUser>(user, false));
}
}
}
@@ -315,20 +311,16 @@ namespace Umbraco.Core.Services
/// Saves an <see cref="IUser"/>
/// </summary>
/// <param name="entity"><see cref="IUser"/> to Save</param>
/// <param name="raiseEvents">Optional parameter to raise events.
/// <param name="raiseEvents">Optional parameter to raise events.
/// Default is <c>True</c> otherwise set to <c>False</c> to not raise events</param>
public void Save(IUser entity, bool raiseEvents = true)
{
using (var uow = UowProvider.GetUnitOfWork())
{
if (raiseEvents)
if (raiseEvents && uow.Events.DispatchCancelable(SavingUser, this, new SaveEventArgs<IUser>(entity)))
{
if (uow.Events.DispatchCancelable(SavingUser, this, new SaveEventArgs<IUser>(entity)))
{
uow.Commit();
return;
}
uow.Commit();
return;
}
if (string.IsNullOrWhiteSpace(entity.Username))
@@ -345,29 +337,34 @@ namespace Umbraco.Core.Services
repository.AddOrUpdate(entity);
try
{
uow.Commit(); // fixme? would throw on dispose not here
// try to flush the unit of work
// ie executes the SQL but does not commit the trx yet
// so we are *not* catching commit exceptions
uow.Commit();
if (raiseEvents)
uow.Events.Dispatch(SavedUser, this, new SaveEventArgs<IUser>(entity, false));
}
catch (DbException ex)
{
//Special case, if we are upgrading and an exception occurs, just continue
// if we are upgrading and an exception occurs, log and swallow it
if (IsUpgrading == false) throw;
Logger.WarnWithException<UserService>("An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored", ex);
return;
// we don't want the uow to rollback its scope! and yet
// we cannot try and uow.Commit() again as it would fail again,
// we have to bypass the uow entirely and complete its inner scope.
// (when the uow disposes, it won't complete the scope again, just dispose it)
uow.Scope.Complete();
}
}
}
/// <summary>
/// Saves a list of <see cref="IUser"/> objects
/// </summary>
/// <param name="entities"><see cref="IEnumerable{IUser}"/> to save</param>
/// <param name="raiseEvents">Optional parameter to raise events.
/// <param name="raiseEvents">Optional parameter to raise events.
/// Default is <c>True</c> otherwise set to <c>False</c> to not raise events</param>
public void Save(IEnumerable<IUser> entities, bool raiseEvents = true)
{
@@ -416,7 +413,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IUser}"/></returns>
public IEnumerable<IUser> FindByEmail(string emailStringToMatch, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
var query = new Query<IUser>();
@@ -457,7 +454,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IUser}"/></returns>
public IEnumerable<IUser> FindByUsername(string login, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
var query = new Query<IUser>();
@@ -499,7 +496,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="System.int"/> with number of Users for passed in type</returns>
public int GetCount(MemberCountType countType)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
@@ -545,7 +542,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IEnumerable{IMember}"/></returns>
public IEnumerable<IUser> GetAll(int pageIndex, int pageSize, out int totalRecords)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
return repository.GetPagedResultsByQuery(null, pageIndex, pageSize, out totalRecords, member => member.Username);
@@ -554,7 +551,7 @@ namespace Umbraco.Core.Services
internal IEnumerable<IUser> GetNextUsers(int id, int count)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = (UserRepository)RepositoryFactory.CreateUserRepository(uow);
return repository.GetNextUsers(id, count);
@@ -594,7 +591,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IUser"/></returns>
public IUser GetUserById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
return repository.Get(id);
@@ -641,7 +638,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="IUserType"/></returns>
public IEnumerable<IUserType> GetAllUserTypes(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserTypeRepository(uow);
return repository.GetAll(ids);
@@ -655,7 +652,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IUserType"/></returns>
public IUserType GetUserTypeByAlias(string alias)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserTypeRepository(uow);
var query = Query<IUserType>.Builder.Where(x => x.Alias == alias);
@@ -670,7 +667,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IUserType"/></returns>
public IUserType GetUserTypeById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserTypeRepository(uow);
return repository.Get(id);
@@ -684,7 +681,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IUserType"/></returns>
public IUserType GetUserTypeByName(string name)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserTypeRepository(uow);
var query = Query<IUserType>.Builder.Where(x => x.Name == name);
@@ -696,28 +693,24 @@ namespace Umbraco.Core.Services
/// Saves a UserType
/// </summary>
/// <param name="userType">UserType to save</param>
/// <param name="raiseEvents">Optional parameter to raise events.
/// <param name="raiseEvents">Optional parameter to raise events.
/// Default is <c>True</c> otherwise set to <c>False</c> to not raise events</param>
public void SaveUserType(IUserType userType, bool raiseEvents = true)
{
using (var uow = UowProvider.GetUnitOfWork())
{
if (raiseEvents)
if (raiseEvents && uow.Events.DispatchCancelable(SavingUserType, this, new SaveEventArgs<IUserType>(userType)))
{
if (uow.Events.DispatchCancelable(SavingUserType, this, new SaveEventArgs<IUserType>(userType)))
{
uow.Commit();
return;
}
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateUserTypeRepository(uow);
repository.AddOrUpdate(userType);
uow.Commit();
if (raiseEvents)
uow.Events.Dispatch(SavedUserType, this, new SaveEventArgs<IUserType>(userType, false));
}
}
/// <summary>
@@ -737,9 +730,7 @@ namespace Umbraco.Core.Services
repository.Delete(userType);
uow.Commit();
uow.Events.Dispatch(DeletedUserType, this, new DeleteEventArgs<IUserType>(userType, false));
}
}
/// <summary>
@@ -804,7 +795,7 @@ namespace Umbraco.Core.Services
/// <returns>An enumerable list of <see cref="EntityPermission"/></returns>
public IEnumerable<EntityPermission> GetPermissions(IUser user, params int[] nodeIds)
{
using (var uow = UowProvider.GetUnitOfWork(commit: true))
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateUserRepository(uow);
var explicitPermissions = repository.GetUserPermissionsForEntities(user.Id, nodeIds);
-2
View File
@@ -698,7 +698,6 @@
<Compile Include="Models\ContentPreviewEntity.cs" />
<Compile Include="Models\ContentTypeBase.cs" />
<Compile Include="Models\ContentTypeCompositionBase.cs" />
<Compile Include="Models\ContentTypeExtensions.cs" />
<Compile Include="Models\ContentTypeSort.cs" />
<Compile Include="Models\ContentXmlEntity.cs" />
<Compile Include="Models\DeepCloneHelper.cs" />
@@ -1196,7 +1195,6 @@
<Compile Include="Persistence\SqlSyntax\SqlSyntaxProviders.cs" />
<Compile Include="Persistence\TransactionType.cs" />
<Compile Include="Persistence\UmbracoDatabase.cs" />
<Compile Include="Persistence\UnitOfWork\FileUnitOfWork.cs" />
<Compile Include="Persistence\UnitOfWork\FileUnitOfWorkProvider.cs" />
<Compile Include="Persistence\UnitOfWork\IDatabaseUnitOfWork.cs" />
<Compile Include="Persistence\UnitOfWork\IDatabaseUnitOfWorkProvider.cs" />
@@ -1,4 +1,6 @@
using System;
using System.IO;
using System.Text;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
@@ -51,6 +53,30 @@ namespace Umbraco.Tests.IO
}
[Test]
public void Media_Fs_Safe_Delete()
{
var fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
var ms = new MemoryStream(Encoding.UTF8.GetBytes("test"));
var virtPath = fs.GetMediaPath("file.txt", Guid.NewGuid(), Guid.NewGuid());
fs.AddFile(virtPath, ms);
// ~/media/1234/file.txt exists
var physPath = IOHelper.MapPath(Path.Combine("media", virtPath));
Assert.IsTrue(File.Exists(physPath));
// ~/media/1234/file.txt is gone
fs.DeleteMediaFiles(new [] { virtPath });
Assert.IsFalse(File.Exists(physPath));
// ~/media/1234 is gone
physPath = Path.GetDirectoryName(physPath);
Assert.IsFalse(Directory.Exists(physPath));
// ~/media exists
physPath = Path.GetDirectoryName(physPath);
Assert.IsTrue(Directory.Exists(physPath));
}
public void Singleton_Typed_File_System()
{
var fs1 = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
@@ -4,8 +4,6 @@ using Umbraco.Core.Logging;
namespace Umbraco.Tests.Logging
{
// FIXME how come some C# 6 features are working here ?!
public class ConsoleLogger : ILogger
{
public void Error(Type callingType, string message, Exception exception)
@@ -63,7 +63,7 @@ namespace Umbraco.Tests.Persistence
//assign the db context
dbContext,
//assign the service context
new ServiceContext(repositoryFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), new FileUnitOfWorkProvider(scopeProvider), cacheHelper, _logger, evtMsgs),
new ServiceContext(repositoryFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), cacheHelper, _logger, evtMsgs),
cacheHelper,
new ProfilingLogger(_logger, Mock.Of<IProfiler>()))
{
@@ -54,7 +54,7 @@ namespace Umbraco.Tests.Scoping
public void Teardown()
{
if (_cacheHandler != null)
_cacheHandler.Destroy();
_cacheHandler.Unbind();
_cacheHandler = null;
ServerRegistrarResolver.Reset();
@@ -90,7 +90,7 @@ namespace Umbraco.Tests.Scoping
Assert.AreEqual(user.Id, globalCached.Id);
Assert.AreEqual("name", globalCached.Name);
_cacheHandler = new CacheRefresherEventHandler();
_cacheHandler = new CacheRefresherEventHandler(true);
_cacheHandler.OnApplicationStarted(null, ApplicationContext);
Assert.IsNull(scopeProvider.AmbientScope);
@@ -171,7 +171,7 @@ namespace Umbraco.Tests.Scoping
Assert.AreEqual(lang.Id, globalCached.Id);
Assert.AreEqual("fr-FR", globalCached.IsoCode);
_cacheHandler = new CacheRefresherEventHandler();
_cacheHandler = new CacheRefresherEventHandler(true);
_cacheHandler.OnApplicationStarted(null, ApplicationContext);
Assert.IsNull(scopeProvider.AmbientScope);
@@ -263,7 +263,7 @@ namespace Umbraco.Tests.Scoping
Assert.AreEqual(item.Id, globalCached.Id);
Assert.AreEqual("item-key", globalCached.ItemKey);
_cacheHandler = new CacheRefresherEventHandler();
_cacheHandler = new CacheRefresherEventHandler(true);
_cacheHandler.OnApplicationStarted(null, ApplicationContext);
Assert.IsNull(scopeProvider.AmbientScope);
+62 -15
View File
@@ -1,11 +1,15 @@
using System;
using System.Collections;
using Moq;
using NUnit.Framework;
using umbraco;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Publishing;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
using Umbraco.Core.Sync;
using Umbraco.Tests.Cache.DistributedCache;
using Umbraco.Tests.TestHelpers;
@@ -42,9 +46,14 @@ namespace Umbraco.Tests.Scoping
public void Teardown()
{
if (_cacheHandler != null)
_cacheHandler.Destroy();
_cacheHandler.Unbind();
_cacheHandler = null;
_onPublishedAssertAction = null;
content.HttpContextItemsGetter = null;
ContentService.Published -= OnPublishedAssert;
SafeXmlReaderWriter.Cloning = null;
ServerRegistrarResolver.Reset();
ServerMessengerResolver.Reset();
CacheRefreshersResolver.Reset();
@@ -63,7 +72,7 @@ namespace Umbraco.Tests.Scoping
var contentType = new ContentType(-1) { Alias = "contenttype", Name = "test"};
ApplicationContext.Services.ContentTypeService.Save(contentType);
_cacheHandler = new CacheRefresherEventHandler();
_cacheHandler = new CacheRefresherEventHandler(true);
_cacheHandler.OnApplicationStarted(null, ApplicationContext);
var xml = content.Instance.XmlContent;
@@ -84,12 +93,23 @@ namespace Umbraco.Tests.Scoping
Assert.IsNotNull(node);
}
private void OnPublishedAssert(IPublishingStrategy sender, PublishEventArgs<IContent> args)
{
if (_onPublishedAssertAction != null)
_onPublishedAssertAction();
}
private Action _onPublishedAssertAction;
[TestCase(true)]
[TestCase(false)]
public void TestScope(bool complete)
{
content.TestingUpdateSitemapProvider = false;
var httpContextItems = new Hashtable();
content.HttpContextItemsGetter = () => httpContextItems;
var settings = SettingsForTests.GenerateMockSettings();
var contentMock = Mock.Get(settings.Content);
contentMock.Setup(x => x.XmlCacheEnabled).Returns(false);
@@ -98,11 +118,12 @@ namespace Umbraco.Tests.Scoping
var contentType = new ContentType(-1) { Alias = "contenttype", Name = "test"};
ApplicationContext.Services.ContentTypeService.Save(contentType);
_cacheHandler = new CacheRefresherEventHandler();
_cacheHandler = new CacheRefresherEventHandler(true);
_cacheHandler.OnApplicationStarted(null, ApplicationContext);
var xml = content.Instance.XmlContent;
Assert.IsNotNull(xml);
Assert.AreSame(xml, httpContextItems[content.XmlContextContentItemKey]);
var beforeXml = xml;
var beforeOuterXml = beforeXml.OuterXml;
var item = new Content("name", -1, contentType);
@@ -110,6 +131,21 @@ namespace Umbraco.Tests.Scoping
Console.WriteLine("Xml Before:");
Console.WriteLine(xml.OuterXml);
var evented = 0;
_onPublishedAssertAction = () =>
{
evented++;
xml = content.Instance.XmlContent;
Assert.IsNotNull(xml);
Assert.AreNotSame(beforeXml, xml);
Console.WriteLine("Xml Event:");
Console.WriteLine(xml.OuterXml);
var node = xml.GetElementById(item.Id.ToString());
Assert.IsNotNull(node);
};
ContentService.Published += OnPublishedAssert;
using (var scope = ApplicationContext.Current.ScopeProvider.CreateScope())
{
ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(item); // should create an xml clone
@@ -119,25 +155,38 @@ namespace Umbraco.Tests.Scoping
// this should never change
Assert.AreEqual(beforeOuterXml, beforeXml.OuterXml);
// this does not change, other thread don't see the changes
xml = content.Instance.XmlContentInternal;
Assert.IsNotNull(xml);
Assert.AreSame(beforeXml, xml);
Console.WriteLine("XmlInternal During:");
Console.WriteLine(xml.OuterXml);
Assert.AreEqual(beforeOuterXml, xml.OuterXml);
// this does not change during the scope (only in events)
// because it is the events that trigger the changes
xml = content.Instance.XmlContent;
Assert.IsNotNull(xml);
Console.WriteLine("Xml After:");
Console.WriteLine(xml.OuterXml);
Assert.AreEqual(beforeOuterXml, xml.OuterXml); // fixme - should it change?
Assert.AreSame(beforeXml, xml);
// note
// this means that, as long as ppl don't create scopes, they'll see their
// changes right after SaveAndPublishWithStatus, but if they create scopes,
// they will have to wail until the scope is completed, ie wait until the
// events trigger, to use eg GetUrl etc
if (complete)
scope.Complete();
}
// fixme - refactor when we have events dispatching,
// the xml clone should prob be only created when the scope completes
Assert.AreEqual(complete ? 2 : 0, evented);
// this should never change
Assert.AreEqual(beforeOuterXml, beforeXml.OuterXml);
xml = content.Instance.XmlContent;
Assert.IsNotNull(xml);
Console.WriteLine("AFTER");
Console.WriteLine("Xml After:");
Console.WriteLine(xml.OuterXml);
if (complete)
{
@@ -146,6 +195,7 @@ namespace Umbraco.Tests.Scoping
}
else
{
Assert.AreSame(beforeXml, xml);
Assert.AreEqual(beforeOuterXml, xml.OuterXml); // nothing has changed!
}
}
@@ -164,7 +214,7 @@ namespace Umbraco.Tests.Scoping
var contentType = new ContentType(-1) { Alias = "contenttype", Name = "test" };
ApplicationContext.Services.ContentTypeService.Save(contentType);
_cacheHandler = new CacheRefresherEventHandler();
_cacheHandler = new CacheRefresherEventHandler(true);
_cacheHandler.OnApplicationStarted(null, ApplicationContext);
var xml = content.Instance.XmlContent;
@@ -199,7 +249,7 @@ namespace Umbraco.Tests.Scoping
Assert.IsNotNull(xml);
Console.WriteLine("Xml InScope (before complete):");
Console.WriteLine(xml.OuterXml);
Assert.AreEqual(beforeOuterXml, xml.OuterXml); // fixme - should it change?
Assert.AreEqual(beforeOuterXml, xml.OuterXml);
if (complete)
scope.Complete();
@@ -208,7 +258,7 @@ namespace Umbraco.Tests.Scoping
Assert.IsNotNull(xml);
Console.WriteLine("Xml InScope (after complete):");
Console.WriteLine(xml.OuterXml);
Assert.AreEqual(beforeOuterXml, xml.OuterXml); // fixme - should it change?
Assert.AreEqual(beforeOuterXml, xml.OuterXml);
}
var scopeProvider = ApplicationContext.Current.ScopeProvider as IScopeProviderInternal;
@@ -220,9 +270,6 @@ namespace Umbraco.Tests.Scoping
// limited number of clones!
Assert.AreEqual(complete ? 1 : 0, clones);
// fixme - refactor when we have events dispatching,
// the xml clone should prob be only created when the scope completes
// this should never change
Assert.AreEqual(beforeOuterXml, beforeXml.OuterXml);
@@ -342,13 +342,13 @@ namespace Umbraco.Tests.Services
public void Get_Descendants()
{
// Arrange
var contentTypeService = ServiceContext.ContentTypeService;
var contentTypeService = (ContentTypeService) ServiceContext.ContentTypeService;
var hierarchy = CreateContentTypeHierarchy();
contentTypeService.Save(hierarchy, 0); //ensure they are saved!
var master = hierarchy.First();
//Act
var descendants = master.Descendants(contentTypeService);
var descendants = contentTypeService.GetDescendants(master);
//Assert
Assert.AreEqual(10, descendants.Count());
@@ -358,13 +358,13 @@ namespace Umbraco.Tests.Services
public void Get_Descendants_And_Self()
{
// Arrange
var contentTypeService = ServiceContext.ContentTypeService;
var contentTypeService = (ContentTypeService) ServiceContext.ContentTypeService;
var hierarchy = CreateContentTypeHierarchy();
contentTypeService.Save(hierarchy, 0); //ensure they are saved!
var master = hierarchy.First();
//Act
var descendants = master.DescendantsAndSelf(contentTypeService);
var descendants = new[] {master}.Concat(contentTypeService.GetDescendants(master));
//Assert
Assert.AreEqual(11, descendants.Count());
@@ -63,9 +63,8 @@ namespace Umbraco.Tests.TestHelpers
var path = TestHelper.CurrentAssemblyDirectory;
AppDomain.CurrentDomain.SetData("DataDirectory", path);
// fixme - in theory we should not need this
// it's done in base.Initialize() and no idea why we do things
// in this order here... not going to change it now though...
// we probably don't need this here, as it's done in base.Initialize() already,
// but these test classes are all weird, not going to change it now - v8
SafeCallContext.Clear();
_dbFactory = new DefaultDatabaseFactory(
@@ -105,7 +104,7 @@ namespace Umbraco.Tests.TestHelpers
//assign the db context
new DatabaseContext(scopeProvider, Logger, SqlSyntax, GetDbProviderName()),
//assign the service context
new ServiceContext(repositoryFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), new FileUnitOfWorkProvider(scopeProvider), CacheHelper, Logger, evtMsgs),
new ServiceContext(repositoryFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), CacheHelper, Logger, evtMsgs),
CacheHelper,
ProfilingLogger)
{
@@ -355,7 +354,7 @@ namespace Umbraco.Tests.TestHelpers
onFail(ex);
}
}
protected DatabaseContext DatabaseContext
{
get { return ApplicationContext.DatabaseContext; }
@@ -170,7 +170,7 @@ namespace Umbraco.Tests.TestHelpers
//assign the db context
new DatabaseContext(scopeProvider, Logger, sqlSyntax, Constants.DatabaseProviders.SqlCe),
//assign the service context
new ServiceContext(repoFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), new FileUnitOfWorkProvider(scopeProvider), CacheHelper, Logger, evtMsgs),
new ServiceContext(repoFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), CacheHelper, Logger, evtMsgs),
CacheHelper,
ProfilingLogger)
{
+1
View File
@@ -594,6 +594,7 @@
<Compile Include="Plugins\TypeFinderTests.cs" />
<Compile Include="Routing\UmbracoModuleTests.cs" />
<Compile Include="VersionExtensionTests.cs" />
<Compile Include="Web\TemplateUtilitiesTests.cs" />
<Compile Include="Web\WebExtensionMethodTests.cs" />
<Compile Include="XmlExtensionsTests.cs" />
<Compile Include="XmlHelperTests.cs" />
@@ -0,0 +1,69 @@
using System;
using System.Linq;
using System.Web;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Profiling;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
using Umbraco.Web.Templates;
namespace Umbraco.Tests.Web
{
[TestFixture]
public class TemplateUtilitiesTests
{
[TestCase("", "")]
[TestCase("hello href=\"{localLink:1234}\" world ", "hello href=\"/my-test-url\" world ")]
[TestCase("hello href=\"{localLink:umb://document-type/9931BDE0-AAC3-4BAB-B838-909A7B47570E}\" world ", "hello href=\"/my-test-url\" world ")]
[TestCase("hello href=\"{localLink:umb://document-type/9931BDE0AAC34BABB838909A7B47570E}\" world ", "hello href=\"/my-test-url\" world ")]
//this one has an invalid char so won't match
[TestCase("hello href=\"{localLink:umb^://document-type/9931BDE0-AAC3-4BAB-B838-909A7B47570E}\" world ", "hello href=\"{localLink:umb^://document-type/9931BDE0-AAC3-4BAB-B838-909A7B47570E}\" world ")]
public void ParseLocalLinks(string input, string result)
{
var serviceCtxMock = MockHelper.GetMockedServiceContext();
//setup a mock entity service from the service context to return an integer for a GUID
var entityService = Mock.Get(serviceCtxMock.EntityService);
entityService.Setup(x => x.GetIdForKey(It.IsAny<Guid>(), It.IsAny<UmbracoObjectTypes>()))
.Returns((Guid id, UmbracoObjectTypes objType) =>
{
return Attempt.Succeed(1234);
});
//setup a mock url provider which we'll use fo rtesting
var testUrlProvider = new Mock<IUrlProvider>();
testUrlProvider.Setup(x => x.GetUrl(It.IsAny<UmbracoContext>(), It.IsAny<int>(), It.IsAny<Uri>(), It.IsAny<UrlProviderMode>()))
.Returns((UmbracoContext umbCtx, int id, Uri url, UrlProviderMode mode) =>
{
return "/my-test-url";
});
using (var appCtx = new ApplicationContext(new DatabaseContext(new Mock<IScopeProviderInternal>().Object, Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test"),
serviceCtxMock,
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())))
using (var umbCtx = UmbracoContext.EnsureContext(
Mock.Of<HttpContextBase>(), appCtx, new Mock<WebSecurity>(null, null).Object,
//setup a quick mock of the WebRouting section
Mock.Of<IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of<IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
//pass in the custom url provider
new[]{ testUrlProvider.Object },
true))
{
var output = TemplateUtilities.ParseInternalLinks(input, umbCtx.UrlProvider);
Assert.AreEqual(result, output);
}
}
}
}
+13 -3
View File
@@ -11,17 +11,17 @@ module.exports = function (grunt) {
//TODO: Too much watching, this brings windows to it's knees when in dev mode
//run by the watch task
grunt.registerTask('watch-js', ['jshint:dev', 'concat', 'copy:app', 'copy:mocks', 'copy:canvasdesigner', 'copy:vs', 'karma:unit']);
grunt.registerTask('watch-less', ['recess:build', 'recess:installer', 'recess:canvasdesigner', 'postcss', 'copy:canvasdesigner', 'copy:assets', 'copy:vs']);
grunt.registerTask('watch-less', ['recess:build', 'recess:installer', 'recess:nonodes', 'recess:canvasdesigner', 'postcss', 'copy:canvasdesigner', 'copy:assets', 'copy:vs']);
grunt.registerTask('watch-html', ['copy:views', 'copy:vs']);
grunt.registerTask('watch-installer', ['concat:install', 'concat:installJs', 'copy:installer', 'copy:vs']);
grunt.registerTask('watch-canvasdesigner', ['copy:canvasdesigner', 'concat:canvasdesignerJs', 'copy:vs']);
grunt.registerTask('watch-test', ['jshint:dev', 'karma:unit']);
//triggered from grunt
grunt.registerTask('build', ['concat', 'recess:build', 'recess:installer', 'recess:canvasdesigner', 'postcss', 'bower-install-simple', 'bower', 'copy', 'clean:post']);
grunt.registerTask('build', ['concat', 'recess:build', 'recess:installer', 'recess:nonodes', 'recess:canvasdesigner', 'postcss', 'bower-install-simple', 'bower', 'copy', 'clean:post']);
//triggered from grunt dev vs or grunt vs
grunt.registerTask('build-dev', ['clean:pre', 'concat', 'recess:build', 'recess:installer', 'postcss', 'bower-install-simple', 'bower', 'copy']);
grunt.registerTask('build-dev', ['clean:pre', 'concat', 'recess:build', 'recess:installer', 'recess:nonodes', 'postcss', 'bower-install-simple', 'bower', 'copy']);
//utillity tasks
grunt.registerTask('docs', ['ngdocs']);
@@ -293,6 +293,16 @@ module.exports = function (grunt) {
compress: true
}
},
nonodes: {
files: {
'<%= distdir %>/assets/css/nonodes.style.min.css':
['src/less/pages/nonodes.less']
},
options: {
compile: true,
compress: true
}
},
installer: {
files: {
'<%= distdir %>/assets/css/installer.css':
@@ -172,8 +172,17 @@ tinymce.PluginManager.add('umbracolink', function(editor) {
//locallink detection, we do this here, to avoid poluting the dialogservice
//so the dialog service can just expect to get a node-like structure
if(currentTarget.url.indexOf("localLink:") > 0){
currentTarget.id = currentTarget.url.substring(currentTarget.url.indexOf(":")+1,currentTarget.url.length-1);
if (currentTarget.url.indexOf("localLink:") > 0) {
var linkId = currentTarget.url.substring(currentTarget.url.indexOf(":") + 1, currentTarget.url.length - 1);
//we need to check if this is an INT or a UDI
var parsedIntId = parseInt(linkId, 10);
if (isNaN(parsedIntId)) {
//it's a UDI
currentTarget.udi = linkId;
}
else {
currentTarget.id = linkId;
}
}
}
@@ -213,7 +222,13 @@ tinymce.PluginManager.add('umbracolink', function(editor) {
//if we have an id, it must be a locallink:id, aslong as the isMedia flag is not set
if(data.id && (angular.isUndefined(data.isMedia) || !data.isMedia)){
href = "/{localLink:" + data.id + "}";
if (target.udi) {
href = "/{localLink:" + target.udi + "}";
}
else {
//This shouldn't happen! but just in case we'll leave this here
href = "/{localLink:" + target.id + "}";
}
insertLink();
return;
}
@@ -1,17 +0,0 @@
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: url('../fonts/opensans/OpenSans-Regular-webfont.eot');
src: local('Open Sans'), local('OpenSans'), url('../fonts/opensans/OpenSans-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/opensans/OpenSans-Regular-webfont.ttf') format('truetype'), url('../fonts/opensans/OpenSans-Regular-webfont.svg#open_sansregular') format('svg');
}
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
src: url('../fonts/opensans/OpenSans-Semibold-webfont.eot');
src: local('Open Sans Semibold'), local('OpenSans-Semibold'), url('../fonts/opensans/OpenSans-Semibold-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/opensans/OpenSans-Semibold-webfont.ttf') format('truetype'), url('../fonts/opensans/OpenSans-Semibold-webfont.svg#open_sanssemibold') format('svg');
}
abbr,address,article,aside,audio,b,blockquote,body,canvas,caption,cite,code,dd,del,details,dfn,div,dl,dt,em,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,nav,object,ol,p,pre,q,samp,section,small,span,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,ul,var,video{margin:0;padding:0;outline:0;border:0;background:0 0;vertical-align:baseline;font-size:100%}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}nav ul{list-style:none}blockquote,q{quotes:none}blockquote:after,blockquote:before,q:after,q:before{content:'';content:none}a{margin:0;padding:0;background:0 0;vertical-align:baseline;font-size:100%}ins{background-color:#ff9;color:#000;text-decoration:none}mark{background-color:#ff9;color:#000;font-weight:700;font-style:italic}del{text-decoration:line-through}abbr[title],dfn[title]{border-bottom:1px dotted;cursor:help}table{border-spacing:0;border-collapse:collapse}hr{display:block;margin:1em 0;padding:0;height:1px;border:0;border-top:1px solid #ccc}input,select{vertical-align:middle}html{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}*,:after,:before{box-sizing:border-box}body,html{height:100%;width:100%;color:#fff;font-family:'Open Sans',sans-serif;font-weight:400;font-size:.9375em;line-height:1.5}h1{font-size:1.7em;margin:40px auto 10px;font-weight:700}h2{font-size:1.35em;margin:0 auto .4em;font-weight:700}h3{font-size:1em;font-weight:400;font-style:italic}p{font-size:1em;line-height:1.6}p+a{margin-top:1rem;display:inline-block}a,a:active,a:visited{text-decoration:none}.cta{margin:4.5em auto 1.5em;padding-bottom:4.5em}.button,.button:visited{padding:.9375em 1.875em;border-radius:.1em;font-weight:600;font-size:1.2em;background:#2e99f4;color:#fff;display:inline-block;border:none;transition:all 200ms ease-in-out}.button:hover,.button:visited:hover{border-bottom:none;background:#0c80e3}section{background:url(../img/nonodesbg.jpg) center center/cover;height:100%;width:100%;display:table;padding:3em 1.75em}section a,section a:focus,section a:visited{color:#46a5f5;font-size:1.1625em;border-bottom:1px solid transparent;transition:border-bottom 100ms ease-in-out}section a:focus:hover,section a:hover,section a:visited:hover{border-bottom:1px solid}section:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.17);background:linear-gradient(45deg,rgba(85,98,112,.1) 10%,rgba(255,107,107,.1) 95%);z-index:0}section article{display:table-cell;vertical-align:middle;margin:0 auto;text-align:center;position:relative;z-index:100}section article>div{max-width:60em;margin:0 auto}section .logo{background:url(../img/logo.png) no-repeat;width:91px;height:91px;margin:0 auto}section .row{overflow:hidden}section .row .col{text-align:left;width:100%}section .row .col:nth-child(2){margin-top:3em}@media screen and (min-width:48em){body,html{font-size:1em}h1{font-size:2.5em;margin:70px auto 0;letter-spacing:.5px}h2{font-size:1.4375em;margin:0 auto 1em}h3{font-size:1.2em}a{font-size:1.1rem;font-weight:600}p+a{margin-top:3rem}.cta{margin:7.5em auto 2.5em;border-bottom:1px solid rgba(255,255,255,.5);padding-bottom:7.5em}section{padding:0 15px}section .row .col{float:left;width:50%;padding-right:5%;display:inline-block}section .row .col:nth-child(2){padding-right:0;padding-left:5%;margin-top:0}.button{font-size:1.1625em}}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 298 KiB

After

Width:  |  Height:  |  Size: 273 KiB

@@ -672,8 +672,17 @@ function tinyMceService(dialogService, $log, imageHelper, $http, $timeout, macro
//locallink detection, we do this here, to avoid poluting the dialogservice
//so the dialog service can just expect to get a node-like structure
if(currentTarget.url.indexOf("localLink:") > 0){
currentTarget.id = currentTarget.url.substring(currentTarget.url.indexOf(":")+1,currentTarget.url.length-1);
if (currentTarget.url.indexOf("localLink:") > 0) {
var linkId = currentTarget.url.substring(currentTarget.url.indexOf(":") + 1, currentTarget.url.length - 1);
//we need to check if this is an INT or a UDI
var parsedIntId = parseInt(linkId, 10);
if (isNaN(parsedIntId)) {
//it's a UDI
currentTarget.udi = linkId;
}
else {
currentTarget.id = linkId;
}
}
}
@@ -747,7 +756,14 @@ function tinyMceService(dialogService, $log, imageHelper, $http, $timeout, macro
//if we have an id, it must be a locallink:id, aslong as the isMedia flag is not set
if(target.id && (angular.isUndefined(target.isMedia) || !target.isMedia)){
href = "/{localLink:" + target.id + "}";
if (target.udi) {
href = "/{localLink:" + target.udi + "}";
}
else {
//This shouldn't happen! but just in case we'll leave this here
href = "/{localLink:" + target.id + "}";
}
insertLink();
return;
}
@@ -100,7 +100,7 @@
<input type="submit" ng-disabled="myForm.$invalid || checking" ng-class="{disabled:myForm.$invalid}"
value="Continue" class="btn btn-success" />
<button class="btn" ng-click="restart()">Go back</button>
<button class="btn btn-info" ng-click="restart()">Go back</button>
<span class="inline-help" ng-if="checking" ng-animate="'fade'">
Validating your database connection...
@@ -8,7 +8,7 @@
To read a report of changes between your current version <strong>{{installer.current.model.currentVersion}}</strong> and this version your upgrading to <strong>{{installer.current.model.newVersion}}</strong>
</p>
<p>
<a ng-href="{{installer.current.model.reportUrl}}" target="_blank" class="btn">View Report</a>
<a ng-href="{{installer.current.model.reportUrl}}" target="_blank" class="btn btn-info">View Report</a>
</p>
<p>
@@ -46,16 +46,21 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="subscribeToNewsLetter" name="subscribeToNewsLetter"
ng-model="installer.current.model.subscribeToNewsLetter" /> Keep me updated on Umbraco Versions, Security Bulletins and Community News</label>
<label>
<input
type="checkbox"
id="subscribeToNewsLetter"
name="subscribeToNewsLetter"
ng-model="installer.current.model.subscribeToNewsLetter" />
Keep me updated on Umbraco Versions, Security Bulletins and Community News
</label>
</div>
</div>
<div class="control-group" ng-class="{disabled:myForm.$invalid}">
<div class="controls">
<input type="submit" ng-disabled="myForm.$invalid" value="Install" class="btn btn-success" />
<a href class="btn btn-neutral control-customize" ng-disabled="myForm.$invalid" ng-click="validateAndForward()">Customize</a>
<a href class="btn btn-info control-customize" ng-disabled="myForm.$invalid" ng-click="validateAndForward()">Customize</a>
</div>
</div>
@@ -19,6 +19,8 @@ body {
line-height: @baseLineHeight;
color: @textColor;
background-color: @bodyBackground;
// better font rendering
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@@ -367,7 +367,7 @@ input.umb-group-builder__group-sort-value {
/* ---------- PLACEHOLDER BOX ---------- */
.umb-group-builder__placeholder-box {
background: @gray-8;
background: @gray-9;
box-sizing: border-box;
display: flex;
align-items: center;
@@ -475,7 +475,7 @@ input.umb-group-builder__group-sort-value {
border-radius: 5px;
color: @gray-3;
font-weight: bold;
font-size: 13px;
font-size: 14px;
color: @turquoise-d1;
&:hover {
text-decoration: none;
@@ -24,7 +24,8 @@
}
.umb-insert-code-box__description {
font-size: 12px;
font-size: 13px;
line-height: 1.6em;
}
.umb-insert-code-box__check {
@@ -331,7 +331,7 @@ input[type="checkbox"]:focus {
// Placeholder text gets special styles because when browsers invalidate entire lines if it doesn't understand a selector
input,
textarea {
.placeholder();
.placeholder(@gray-6);
}
@@ -3,7 +3,7 @@
padding: 1px 5px;
background: @red;
color: @white;
font-size: 10px;
font-size: 11px;
line-height: 1.5em;
}
@@ -40,6 +40,12 @@ body {
vertical-align: middle;
text-align: center;
// better font rendering
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#logo{
@@ -116,7 +122,7 @@ body {
h1{
border-bottom: 1px solid @gray-10;
padding-bottom: 10px;
color: @gray-3;
color: @gray-2;
}
.error h1, .error .message, span.error{ color: @red;}
@@ -128,6 +134,12 @@ input.ng-dirty.ng-invalid{border-color: #b94a48; color: #b94a48;}
opacity: 0.6;
}
#installer label.control-label,
#installer .constrol-label {
padding-top: 5px !important;
}
.controls{
text-align: left
}
@@ -0,0 +1,367 @@
@import "../fonts.less"; // Loading fonts
@import "../variables.less"; // Loading variables
abbr,
address,
article,
aside,
audio,
b,
blockquote,
body,
canvas,
caption,
cite,
code,
dd,
del,
details,
dfn,
div,
dl,
dt,
em,
fieldset,
figcaption,
figure,
footer,
form,
h1,
h2,
h3,
h4,
h5,
h6,
header,
hgroup,
html,
i,
iframe,
img,
ins,
kbd,
label,
legend,
li,
mark,
menu,
nav,
object,
ol,
p,
pre,
q,
samp,
section,
small,
span,
strong,
sub,
summary,
sup,
table,
tbody,
td,
tfoot,
th,
thead,
time,
tr,
ul,
var,
video {
margin: 0;
padding: 0;
outline: 0;
border: 0;
background: 0 0;
vertical-align: baseline;
font-size: 100%;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
nav ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:after,
blockquote:before,
q:after,
q:before {
content: '';
content: none;
}
a {
margin: 0;
padding: 0;
background: 0 0;
vertical-align: baseline;
font-size: 100%;
}
ins {
background-color: @yellow-l3;
color: @black;
text-decoration: none;
}
mark {
background-color: @yellow-l3;
color: @black;
font-weight: bold;
font-style: italic;
}
del {
text-decoration: line-through;
}
abbr[title],
dfn[title] {
border-bottom: 1px dotted;
cursor: help;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
hr {
display: block;
margin: 1em 0;
padding: 0;
height: 1px;
border: 0;
border-top: 1px solid @gray-8;
}
input,
select {
vertical-align: middle;
}
html {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
*,
:after,
:before {
box-sizing: border-box;
}
body,
html {
height: 100%;
width: 100%;
color: @white;
font-family: @sansFontFamily;
font-weight: 400;
font-size: .9375em;
line-height: 1.5;
}
h1 {
font-size: 1.7em;
margin: 40px auto 10px;
font-weight: 700;
}
h2 {
font-size: 1.35em;
margin: 0 auto .4em;
font-weight: 700;
}
h3 {
font-size: 1em;
font-weight: 400;
font-style: italic;
}
p {
font-size: 1em;
line-height: 1.6;
}
p+a {
margin-top: 1rem;
display: inline-block;
}
a,
a:active,
a:visited {
text-decoration: none;
}
.cta {
margin: 4.5em auto 1.5em;
padding-bottom: 4.5em;
}
.button,
.button:visited {
padding: .9375em 1.875em;
border-radius: .1em;
font-weight: 600;
font-size: 1.2em;
background: @green;
color: @white;
display: inline-block;
border: none;
transition: all 200ms ease-in-out;
border-radius: 3px;
}
.button:hover,
.button:visited:hover {
border-bottom: none;
background: @green-d1;
}
section {
background-image: url(../img/nonodesbg.jpg);
background-position: center center;
background-size: cover;
height: 100%;
width: 100%;
display: table;
padding: 3em 1.75em
}
section a,
section a:focus,
section a:visited {
color: @white;
font-size: 1.1625em;
border-bottom: 1px solid @white;
transition: border-bottom 100ms ease-in-out;
}
section a:focus:hover,
section a:hover,
section a:visited:hover {
border-bottom: 1px solid;
}
section:after {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, .17);
background: linear-gradient(45deg, rgba(85, 98, 112, .1) 10%, rgba(255, 107, 107, .1) 95%);
z-index: 0
}
section article {
display: table-cell;
vertical-align: middle;
margin: 0 auto;
text-align: center;
position: relative;
z-index: 100;
}
section article>div {
max-width: 60em;
margin: 0 auto;
padding-top: 50px;
padding-bottom: 70px;
}
section .logo {
background-image: url(../img/logo.png);
background-repeat: no-repeat;
width: 91px;
height: 91px;
margin: 0 auto;
}
section .row {
overflow: hidden;
}
section .row .col {
text-align: left;
width: 100%;
}
section .row .col:nth-child(2) {
margin-top: 3em;
}
@media screen and (min-width:48em) {
body,
html {
font-size: 1em;
}
h1 {
font-size: 2.5em;
margin: 70px auto 0;
letter-spacing: .5px;
}
h2 {
font-size: 1.4375em;
margin: 0 auto 1em;
}
h3 {
font-size: 1.2em;
}
a {
font-size: 1.1rem;
font-weight: 600;
}
p+a {
margin-top: 3rem;
}
.cta {
margin: 7.5em auto 2.5em;
border-bottom: 1px solid @gray-5;
padding-bottom: 7.5em;
}
section {
padding: 0 15px;
}
section .row .col {
float: left;
width: 50%;
padding-right: 5%;
display: inline-block;
}
section .row .col:nth-child(2) {
padding-right: 0;
padding-left: 5%;
margin-top: 0;
}
.button {
font-size: 1.1625em;
}
}
@@ -470,7 +470,7 @@ input.umb-panel-header-description {
background: transparent;
border-color: transparent;
margin-bottom: 0;
font-size: 12px;
font-size: 13px;
box-sizing: border-box;
height: 25px;
line-height: 25px;
@@ -51,7 +51,7 @@ ul.sections li a {
}
ul.sections a span {
font-size: 10px;
font-size: 11px;
line-height: 1.4em;
opacity: 0;
-webkit-transition: all .3s linear;
+12 -10
View File
@@ -119,10 +119,9 @@
.umb-tree li.root > div a,
.umb-tree li.root h5, .umb-tree-header {
text-transform: uppercase;
color: @gray-7;
color: @gray-2;
font-weight: bold;
font-size: 13px;
font-size: 15px;
}
.umb-tree ins {
@@ -377,12 +376,15 @@ div.locked:before{
.umb-actions a {
white-space: nowrap;
display: block;
font-size: 14px;
font-size: 15px;
color: @black;
padding: 8px 25px 8px 20px;
padding: 9px 25px 9px 20px;
text-decoration: none;
cursor: pointer;
display: flex;
align-items: center;
}
.umb-actions a:hover, .umb-actions a:focus,
.umb-actions li.selected {
color: @black !important;
@@ -393,11 +395,10 @@ div.locked:before{
display: inline-block;
vertical-align: middle;
padding-left: 15px;
padding-top: 2px;
}
.umb-actions i {
color: @gray-6;
margin-top: 2px;
font-size: 18px;
vertical-align: middle;
color: @gray-3;
@@ -430,15 +431,16 @@ div.locked:before{
display: block;
clear: right;
line-height: 14px;
color: @gray-7;
color: @gray-6;
white-space: normal;
margin-top: 2px;
}
.umb-actions-child li a:hover .menuLabel small {
text-decoration: none !important
}
.umb-actions-child i {
font-size: 32px;
min-width: 32px;
font-size: 30px;
min-width: 30px;
text-align: center;
line-height: 24px; /* set line-height to ensure all icons use same line-height */
}
@@ -26,17 +26,21 @@ angular.module("umbraco").controller("Umbraco.Overlays.LinkPickerController",
$scope.model.target = dialogOptions.currentTarget;
//if we have a node ID, we fetch the current node to build the form data
if ($scope.model.target.id) {
if ($scope.model.target.id || $scope.model.target.udi) {
if (!$scope.model.target.path) {
entityResource.getPath($scope.model.target.id, "Document").then(function (path) {
//will be either a udi or an int
var id = $scope.model.target.udi ? $scope.model.target.udi : $scope.model.target.id;
if (!$scope.model.target.path) {
entityResource.getPath(id, "Document").then(function (path) {
$scope.model.target.path = path;
//now sync the tree to this path
$scope.dialogTreeEventHandler.syncTree({ path: $scope.model.target.path, tree: "content" });
});
}
contentResource.getNiceUrl($scope.model.target.id).then(function (url) {
contentResource.getNiceUrl(id).then(function (url) {
$scope.model.target.url = url;
});
}
@@ -63,7 +67,8 @@ angular.module("umbraco").controller("Umbraco.Overlays.LinkPickerController",
$scope.currentNode = args.node;
$scope.currentNode.selected = true;
$scope.model.target.id = args.node.id;
$scope.model.target.id = args.node.id;
$scope.model.target.udi = args.node.udi;
$scope.model.target.name = args.node.name;
if (args.node.id < 0) {
@@ -116,7 +121,8 @@ angular.module("umbraco").controller("Umbraco.Overlays.LinkPickerController",
submit: function(model) {
var media = model.selectedImages[0];
$scope.model.target.id = media.id;
$scope.model.target.id = media.id;
$scope.model.target.udi = media.udi;
$scope.model.target.isMedia = true;
$scope.model.target.name = media.name;
$scope.model.target.url = mediaHelper.resolveFile(media);
@@ -13,17 +13,6 @@
<trace enabled="false" xdt:Transform="SetAttributes(enabled)" />
<customErrors mode="RemoteOnly" xdt:Transform="SetAttributes(mode)">
</customErrors>
<membership>
<providers>
<add xdt:Transform="SetAttributes(useLegacyEncoding,minRequiredPasswordLength)" xdt:Locator="Match(name)" name="UmbracoMembershipProvider"
minRequiredPasswordLength="8"
useLegacyEncoding="true" />
<add xdt:Transform="SetAttributes(useLegacyEncoding,minRequiredPasswordLength)" xdt:Locator="Match(name)" name="UsersMembershipProvider"
minRequiredPasswordLength="8"
useLegacyEncoding="true" />
</providers>
</membership>
</system.web>
+2 -2
View File
@@ -248,8 +248,8 @@
<membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="UmbracoMembershipProvider" type="Umbraco.Web.Security.Providers.MembersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed" />
<add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" passwordFormat="Hashed" />
<add name="UmbracoMembershipProvider" type="Umbraco.Web.Security.Providers.MembersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="10" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed" allowManuallyChangingPassword="false" />
<add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="10" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" allowManuallyChangingPassword="false" />
</providers>
</membership>
<!-- Role Provider -->
@@ -26,219 +26,189 @@ namespace Umbraco.Web.Cache
[Weight(int.MinValue)]
public class CacheRefresherEventHandler : ApplicationEventHandler
{
public CacheRefresherEventHandler()
{ }
public CacheRefresherEventHandler(bool supportUnbinding)
{
if (supportUnbinding)
_unbinders = new List<Action>();
}
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
LogHelper.Info<CacheRefresherEventHandler>("Initializing Umbraco internal event handlers for cache refreshing");
//bind to application tree events
ApplicationTreeService.Deleted += ApplicationTreeService_Deleted;
ApplicationTreeService.Updated += ApplicationTreeService_Updated;
ApplicationTreeService.New += ApplicationTreeService_New;
// bind to application tree events
Bind(() => ApplicationTreeService.Deleted += ApplicationTreeService_Deleted,
() => ApplicationTreeService.Deleted -= ApplicationTreeService_Deleted);
Bind(() => ApplicationTreeService.Updated += ApplicationTreeService_Updated,
() => ApplicationTreeService.Updated -= ApplicationTreeService_Updated);
Bind(() => ApplicationTreeService.New += ApplicationTreeService_New,
() => ApplicationTreeService.New -= ApplicationTreeService_New);
//bind to application events
SectionService.Deleted += SectionService_Deleted;
SectionService.New += SectionService_New;
// bind to application events
Bind(() => SectionService.Deleted += SectionService_Deleted,
() => SectionService.Deleted -= SectionService_Deleted);
Bind(() => SectionService.New += SectionService_New,
() => SectionService.New -= SectionService_New);
//bind to user / user type events
UserService.SavedUserType += UserService_SavedUserType;
UserService.DeletedUserType += UserService_DeletedUserType;
UserService.SavedUser += UserService_SavedUser;
UserService.DeletedUser += UserService_DeletedUser;
// bind to user and user type events
Bind(() => UserService.SavedUserType += UserService_SavedUserType,
() => UserService.SavedUserType -= UserService_SavedUserType);
Bind(() => UserService.DeletedUserType += UserService_DeletedUserType,
() => UserService.DeletedUserType -= UserService_DeletedUserType);
Bind(() => UserService.SavedUser += UserService_SavedUser,
() => UserService.SavedUser -= UserService_SavedUser);
Bind(() => UserService.DeletedUser += UserService_DeletedUser,
() => UserService.DeletedUser -= UserService_DeletedUser);
//Bind to dictionary events
// bind to dictionary events
Bind(() => LocalizationService.DeletedDictionaryItem += LocalizationService_DeletedDictionaryItem,
() => LocalizationService.DeletedDictionaryItem -= LocalizationService_DeletedDictionaryItem);
Bind(() => LocalizationService.SavedDictionaryItem += LocalizationService_SavedDictionaryItem,
() => LocalizationService.SavedDictionaryItem -= LocalizationService_SavedDictionaryItem);
LocalizationService.DeletedDictionaryItem += LocalizationService_DeletedDictionaryItem;
LocalizationService.SavedDictionaryItem += LocalizationService_SavedDictionaryItem;
// bind to data type events
Bind(() => DataTypeService.Deleted += DataTypeService_Deleted,
() => DataTypeService.Deleted -= DataTypeService_Deleted);
Bind(() => DataTypeService.Saved += DataTypeService_Saved,
() => DataTypeService.Saved -= DataTypeService_Saved);
//Bind to data type events
//NOTE: we need to bind to legacy and new API events currently: http://issues.umbraco.org/issue/U4-1979
// bind to stylesheet events
Bind(() => FileService.SavedStylesheet += FileService_SavedStylesheet,
() => FileService.SavedStylesheet -= FileService_SavedStylesheet);
Bind(() => FileService.DeletedStylesheet += FileService_DeletedStylesheet,
() => FileService.DeletedStylesheet -= FileService_DeletedStylesheet);
DataTypeService.Deleted += DataTypeService_Deleted;
DataTypeService.Saved += DataTypeService_Saved;
// bind to domain events
Bind(() => DomainService.Saved += DomainService_Saved,
() => DomainService.Saved -= DomainService_Saved);
Bind(() => DomainService.Deleted += DomainService_Deleted,
() => DomainService.Deleted -= DomainService_Deleted);
//Bind to stylesheet events
// bind to language events
Bind(() => LocalizationService.SavedLanguage += LocalizationService_SavedLanguage,
() => LocalizationService.SavedLanguage -= LocalizationService_SavedLanguage);
Bind(() => LocalizationService.DeletedLanguage += LocalizationService_DeletedLanguage,
() => LocalizationService.DeletedLanguage -= LocalizationService_DeletedLanguage);
FileService.SavedStylesheet += FileService_SavedStylesheet;
FileService.DeletedStylesheet += FileService_DeletedStylesheet;
// bind to content type events
Bind(() => ContentTypeService.SavedContentType += ContentTypeService_SavedContentType,
() => ContentTypeService.SavedContentType -= ContentTypeService_SavedContentType);
Bind(() => ContentTypeService.SavedMediaType += ContentTypeService_SavedMediaType,
() => ContentTypeService.SavedMediaType -= ContentTypeService_SavedMediaType);
Bind(() => ContentTypeService.DeletedContentType += ContentTypeService_DeletedContentType,
() => ContentTypeService.DeletedContentType -= ContentTypeService_DeletedContentType);
Bind(() => ContentTypeService.DeletedMediaType += ContentTypeService_DeletedMediaType,
() => ContentTypeService.DeletedMediaType -= ContentTypeService_DeletedMediaType);
Bind(() => MemberTypeService.Saved += MemberTypeService_Saved,
() => MemberTypeService.Saved -= MemberTypeService_Saved);
Bind(() => MemberTypeService.Deleted += MemberTypeService_Deleted,
() => MemberTypeService.Deleted -= MemberTypeService_Deleted);
//Bind to domain events
// bind to permission events
// we should wrap legacy permissions so we can get rid of this
// fixme - the method names here (PermissionNew...) are not supported
// by the event handling mechanism for scopes and deploy, and not sure
// how to fix with the generic repository
Bind(() => Permission.New += PermissionNew,
() => Permission.New -= PermissionNew);
Bind(() => Permission.Updated += PermissionUpdated,
() => Permission.Updated -= PermissionUpdated);
Bind(() => Permission.Deleted += PermissionDeleted,
() => Permission.Deleted -= PermissionDeleted);
Bind(() => PermissionRepository<IContent>.AssignedPermissions += CacheRefresherEventHandler_AssignedPermissions,
() => PermissionRepository<IContent>.AssignedPermissions -= CacheRefresherEventHandler_AssignedPermissions);
DomainService.Saved += DomainService_Saved;
DomainService.Deleted += DomainService_Deleted;
// bind to template events
Bind(() => FileService.SavedTemplate += FileService_SavedTemplate,
() => FileService.SavedTemplate -= FileService_SavedTemplate);
Bind(() => FileService.DeletedTemplate += FileService_DeletedTemplate,
() => FileService.DeletedTemplate -= FileService_DeletedTemplate);
//Bind to language events
// bind to macro events
Bind(() => MacroService.Saved += MacroService_Saved,
() => MacroService.Saved -= MacroService_Saved);
Bind(() => MacroService.Deleted += MacroService_Deleted,
() => MacroService.Deleted -= MacroService_Deleted);
LocalizationService.SavedLanguage += LocalizationService_SavedLanguage;
LocalizationService.DeletedLanguage += LocalizationService_DeletedLanguage;
// bind to member events
Bind(() => MemberService.Saved += MemberService_Saved,
() => MemberService.Saved -= MemberService_Saved);
Bind(() => MemberService.Deleted += MemberService_Deleted,
() => MemberService.Deleted -= MemberService_Deleted);
Bind(() => MemberGroupService.Saved += MemberGroupService_Saved,
() => MemberGroupService.Saved -= MemberGroupService_Saved);
Bind(() => MemberGroupService.Deleted += MemberGroupService_Deleted,
() => MemberGroupService.Deleted -= MemberGroupService_Deleted);
//Bind to content type events
// bind to media events
Bind(() => MediaService.Saved += MediaService_Saved,
() => MediaService.Saved -= MediaService_Saved);
Bind(() => MediaService.Deleted += MediaService_Deleted,
() => MediaService.Deleted -= MediaService_Deleted);
Bind(() => MediaService.Moved += MediaService_Moved,
() => MediaService.Moved -= MediaService_Moved);
Bind(() => MediaService.Trashed += MediaService_Trashed,
() => MediaService.Trashed -= MediaService_Trashed);
Bind(() => MediaService.EmptiedRecycleBin += MediaService_EmptiedRecycleBin,
() => MediaService.EmptiedRecycleBin -= MediaService_EmptiedRecycleBin);
ContentTypeService.SavedContentType += ContentTypeService_SavedContentType;
ContentTypeService.SavedMediaType += ContentTypeService_SavedMediaType;
ContentTypeService.DeletedContentType += ContentTypeService_DeletedContentType;
ContentTypeService.DeletedMediaType += ContentTypeService_DeletedMediaType;
MemberTypeService.Saved += MemberTypeService_Saved;
MemberTypeService.Deleted += MemberTypeService_Deleted;
// bind to content events
// this is for unpublished content syncing across servers (primarily for examine)
Bind(() => ContentService.Saved += ContentService_Saved,
() => ContentService.Saved -= ContentService_Saved);
Bind(() => ContentService.Deleted += ContentService_Deleted,
() => ContentService.Deleted -= ContentService_Deleted);
Bind(() => ContentService.Copied += ContentService_Copied,
() => ContentService.Copied -= ContentService_Copied);
// the Move method of the content service fires Saved/Published events during its
// execution so we don't need to listen to moved - this will probably change in due time
//Bind(() => ContentService.Moved += ContentServiceMoved,
// () => ContentService.Moved -= ContentServiceMoved);
Bind(() => ContentService.Trashed += ContentService_Trashed,
() => ContentService.Trashed -= ContentService_Trashed);
Bind(() => ContentService.EmptiedRecycleBin += ContentService_EmptiedRecycleBin,
() => ContentService.EmptiedRecycleBin -= ContentService_EmptiedRecycleBin);
Bind(() => ContentService.Published += ContentService_Published,
() => ContentService.Published -= ContentService_Published);
Bind(() => ContentService.UnPublished += ContentService_UnPublished,
() => ContentService.UnPublished -= ContentService_UnPublished);
//Bind to permission events
// bind to public access events
Bind(() => PublicAccessService.Saved += PublicAccessService_Saved,
() => PublicAccessService.Saved -= PublicAccessService_Saved);
Bind(() => PublicAccessService.Deleted += PublicAccessService_Deleted,
() => PublicAccessService.Deleted -= PublicAccessService_Deleted);
//TODO: Wrap legacy permissions so we can get rid of this
Permission.New += PermissionNew;
Permission.Updated += PermissionUpdated;
Permission.Deleted += PermissionDeleted;
PermissionRepository<IContent>.AssignedPermissions += CacheRefresherEventHandler_AssignedPermissions;
// bind to relation type events
Bind(() => RelationService.SavedRelationType += RelationService_SavedRelationType,
() => RelationService.SavedRelationType -= RelationService_SavedRelationType);
Bind(() => RelationService.DeletedRelationType += RelationService_DeletedRelationType,
() => RelationService.DeletedRelationType -= RelationService_DeletedRelationType);
}
//Bind to template events
private List<Action> _unbinders;
FileService.SavedTemplate += FileService_SavedTemplate;
FileService.DeletedTemplate += FileService_DeletedTemplate;
private void Bind(Action binder, Action unbinder)
{
// bind now
binder();
//Bind to macro events
MacroService.Saved += MacroService_Saved;
MacroService.Deleted += MacroService_Deleted;
//Bind to member events
MemberService.Saved += MemberService_Saved;
MemberService.Deleted += MemberService_Deleted;
MemberGroupService.Saved += MemberGroupService_Saved;
MemberGroupService.Deleted += MemberGroupService_Deleted;
//Bind to media events
MediaService.Saved += MediaService_Saved;
MediaService.Deleted += MediaService_Deleted;
MediaService.Moved += MediaService_Moved;
MediaService.Trashed += MediaService_Trashed;
MediaService.EmptiedRecycleBin += MediaService_EmptiedRecycleBin;
//Bind to content events - this is for unpublished content syncing across servers (primarily for examine)
ContentService.Saved += ContentService_Saved;
ContentService.Deleted += ContentService_Deleted;
ContentService.Copied += ContentService_Copied;
//TODO: The Move method of the content service fires Saved/Published events during its execution so we don't need to listen to moved
//ContentService.Moved += ContentServiceMoved;
ContentService.Trashed += ContentService_Trashed;
ContentService.EmptiedRecycleBin += ContentService_EmptiedRecycleBin;
ContentService.Published += ContentService_Published;
ContentService.UnPublished += ContentService_UnPublished;
//public access events
PublicAccessService.Saved += PublicAccessService_Saved;
PublicAccessService.Deleted += PublicAccessService_Deleted;
RelationService.SavedRelationType += RelationService_SavedRelationType;
RelationService.DeletedRelationType += RelationService_DeletedRelationType;
// abd register unbinder for later, if needed
if (_unbinders == null) return;
_unbinders.Add(unbinder);
}
// for tests
internal void Destroy()
internal void Unbind()
{
//bind to application tree events
ApplicationTreeService.Deleted -= ApplicationTreeService_Deleted;
ApplicationTreeService.Updated -= ApplicationTreeService_Updated;
ApplicationTreeService.New -= ApplicationTreeService_New;
//bind to application events
SectionService.Deleted -= SectionService_Deleted;
SectionService.New -= SectionService_New;
//bind to user / user type events
UserService.SavedUserType -= UserService_SavedUserType;
UserService.DeletedUserType -= UserService_DeletedUserType;
UserService.SavedUser -= UserService_SavedUser;
UserService.DeletedUser -= UserService_DeletedUser;
//Bind to dictionary events
LocalizationService.DeletedDictionaryItem -= LocalizationService_DeletedDictionaryItem;
LocalizationService.SavedDictionaryItem -= LocalizationService_SavedDictionaryItem;
//Bind to data type events
//NOTE: we need to bind to legacy and new API events currently: http://issues.umbraco.org/issue/U4-1979
DataTypeService.Deleted -= DataTypeService_Deleted;
DataTypeService.Saved -= DataTypeService_Saved;
//Bind to stylesheet events
FileService.SavedStylesheet -= FileService_SavedStylesheet;
FileService.DeletedStylesheet -= FileService_DeletedStylesheet;
//Bind to domain events
DomainService.Saved -= DomainService_Saved;
DomainService.Deleted -= DomainService_Deleted;
//Bind to language events
LocalizationService.SavedLanguage -= LocalizationService_SavedLanguage;
LocalizationService.DeletedLanguage -= LocalizationService_DeletedLanguage;
//Bind to content type events
ContentTypeService.SavedContentType -= ContentTypeService_SavedContentType;
ContentTypeService.SavedMediaType -= ContentTypeService_SavedMediaType;
ContentTypeService.DeletedContentType -= ContentTypeService_DeletedContentType;
ContentTypeService.DeletedMediaType -= ContentTypeService_DeletedMediaType;
MemberTypeService.Saved -= MemberTypeService_Saved;
MemberTypeService.Deleted -= MemberTypeService_Deleted;
//Bind to permission events
//TODO: Wrap legacy permissions so we can get rid of this
Permission.New -= PermissionNew;
Permission.Updated -= PermissionUpdated;
Permission.Deleted -= PermissionDeleted;
PermissionRepository<IContent>.AssignedPermissions -= CacheRefresherEventHandler_AssignedPermissions;
//Bind to template events
FileService.SavedTemplate -= FileService_SavedTemplate;
FileService.DeletedTemplate -= FileService_DeletedTemplate;
//Bind to macro events
MacroService.Saved -= MacroService_Saved;
MacroService.Deleted -= MacroService_Deleted;
//Bind to member events
MemberService.Saved -= MemberService_Saved;
MemberService.Deleted -= MemberService_Deleted;
MemberGroupService.Saved -= MemberGroupService_Saved;
MemberGroupService.Deleted -= MemberGroupService_Deleted;
//Bind to media events
MediaService.Saved -= MediaService_Saved;
MediaService.Deleted -= MediaService_Deleted;
MediaService.Moved -= MediaService_Moved;
MediaService.Trashed -= MediaService_Trashed;
MediaService.EmptiedRecycleBin -= MediaService_EmptiedRecycleBin;
//Bind to content events - this is for unpublished content syncing across servers (primarily for examine)
ContentService.Saved -= ContentService_Saved;
ContentService.Deleted -= ContentService_Deleted;
ContentService.Copied -= ContentService_Copied;
//TODO: The Move method of the content service fires Saved/Published events during its execution so we don't need to listen to moved
//ContentService.Moved -= ContentServiceMoved;
ContentService.Trashed -= ContentService_Trashed;
ContentService.EmptiedRecycleBin -= ContentService_EmptiedRecycleBin;
ContentService.Published -= ContentService_Published;
ContentService.UnPublished -= ContentService_UnPublished;
//public access events
PublicAccessService.Saved -= PublicAccessService_Saved;
PublicAccessService.Deleted -= PublicAccessService_Deleted;
RelationService.SavedRelationType -= RelationService_SavedRelationType;
RelationService.DeletedRelationType -= RelationService_DeletedRelationType;
if (_unbinders == null)
throw new NotSupportedException();
foreach (var unbinder in _unbinders)
unbinder();
_unbinders = null;
}
#region Publishing
@@ -247,11 +217,13 @@ namespace Umbraco.Web.Cache
// events are actually raised, but not when they are handled by HandleEvents, so we have to have
// these proxy methods that are *not* registered against any event *but* used by HandleEvents.
// ReSharper disable once UnusedMember.Local
static void PublishingStrategy_UnPublished(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
ContentService_UnPublished(sender, e);
}
// ReSharper disable once UnusedMember.Local
static void PublishingStrategy_Published(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
ContentService_Published(sender, e);
@@ -633,8 +605,7 @@ namespace Umbraco.Web.Cache
#endregion
#region User/permissions event handlers
//fixme: this isn't named correct
static void CacheRefresherEventHandler_AssignedPermissions(PermissionRepository<IContent> sender, SaveEventArgs<EntityPermission> e)
{
var userIds = e.SavedEntities.Select(x => x.UserId).Distinct();
@@ -822,7 +793,7 @@ namespace Umbraco.Web.Cache
var handler = FindHandler(e);
if (handler == null) continue;
handler.Invoke(null, new object[] { e.Sender, e.Args });
handler.Invoke(null, new[] { e.Sender, e.Args });
}
}
@@ -831,21 +802,24 @@ namespace Umbraco.Web.Cache
/// </summary>
private static readonly Lazy<MethodInfo[]> CandidateHandlers = new Lazy<MethodInfo[]>(() =>
{
var candidates =
var underscore = new[] { '_' };
typeof(CacheRefresherEventHandler).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.Name.Contains("_"))
.Select(x => new
{
method = x,
nameParts = x.Name.Split(new[] { "_" }, StringSplitOptions.RemoveEmptyEntries),
methodParams = x.GetParameters()
})
.Where(x => x.nameParts.Length == 2 && x.methodParams.Length == 2 && typeof(EventArgs).IsAssignableFrom(x.methodParams[1].ParameterType))
.Select(x => x.method)
.ToArray();
return typeof (CacheRefresherEventHandler)
.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Select(x =>
{
if (x.Name.Contains("_") == false) return null;
return candidates;
var parts = x.Name.Split(underscore, StringSplitOptions.RemoveEmptyEntries).Length;
if (parts != 2) return null;
var parameters = x.GetParameters();
if (parameters.Length != 2) return null;
if (typeof (EventArgs).IsAssignableFrom(parameters[1].ParameterType) == false) return null;
return x;
})
.WhereNotNull()
.ToArray();
});
/// <summary>
@@ -855,14 +829,9 @@ namespace Umbraco.Web.Cache
internal static MethodInfo FindHandler(IEventDefinition eventDefinition)
{
return FoundHandlers.GetOrAdd(eventDefinition, definition =>
{
var candidates = CandidateHandlers.Value;
var name = eventDefinition.Sender.GetType().Name + "_" + eventDefinition.EventName;
var found = candidates.FirstOrDefault(x => x.Name == string.Format("{0}_{1}", eventDefinition.Sender.GetType().Name, eventDefinition.EventName));
return found;
});
return FoundHandlers.GetOrAdd(eventDefinition, _ => CandidateHandlers.Value.FirstOrDefault(x => x.Name == name));
}
}
}
@@ -9,7 +9,7 @@ using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Services;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
@@ -47,6 +47,7 @@ namespace Umbraco.Web.Cache
/// <returns></returns>
internal static JsonPayload FromContentType(IContentTypeBase contentType, bool isDeleted = false)
{
var contentTypeService = (ContentTypeService) ApplicationContext.Current.Services.ContentTypeService;
var payload = new JsonPayload
{
Alias = contentType.Alias,
@@ -58,7 +59,7 @@ namespace Umbraco.Web.Cache
: (contentType is IMediaType)
? typeof(IMediaType).Name
: typeof(IMemberType).Name,
DescendantPayloads = contentType.Descendants(ApplicationContext.Current.Services.ContentTypeService).Select(x => FromContentType(x)).ToArray(),
DescendantPayloads = contentTypeService.GetDescendants(contentType).Select(x => FromContentType(x)).ToArray(),
WasDeleted = isDeleted,
PropertyRemoved = contentType.WasPropertyDirty("HasPropertyTypeBeenRemoved"),
AliasChanged = contentType.WasPropertyDirty("Alias"),
+1 -1
View File
@@ -50,7 +50,7 @@ namespace Umbraco.Web.Cache
/// </summary>
public override void RefreshAll()
{
content.Instance.RefreshContentFromDatabaseAsync();
content.Instance.RefreshContentFromDatabase();
base.RefreshAll();
}
+43 -1
View File
@@ -6,6 +6,7 @@ using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using AutoMapper;
using Umbraco.Core;
@@ -35,7 +36,8 @@ namespace Umbraco.Web.Editors
/// access to ALL of the methods on this controller will need access to the content application.
/// </remarks>
[PluginController("UmbracoApi")]
[UmbracoApplicationAuthorizeAttribute(Constants.Applications.Content)]
[UmbracoApplicationAuthorize(Constants.Applications.Content)]
[ContentControllerConfiguration]
public class ContentController : ContentControllerBase
{
/// <summary>
@@ -55,6 +57,18 @@ namespace Umbraco.Web.Editors
{
}
/// <summary>
/// Configures this controller with a custom action selector
/// </summary>
private class ContentControllerConfigurationAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
controllerSettings.Services.Replace(typeof(IHttpActionSelector), new ParameterSwapControllerActionSelector(
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetNiceUrl", "id", typeof(int), typeof(Guid), typeof(Udi))));
}
}
/// <summary>
/// Return content for the specified ids
/// </summary>
@@ -162,6 +176,34 @@ namespace Umbraco.Web.Editors
return response;
}
/// <summary>
/// Gets the Url for a given node ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public HttpResponseMessage GetNiceUrl(Guid id)
{
var url = Umbraco.UrlProvider.GetUrl(id);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(url, Encoding.UTF8, "application/json");
return response;
}
/// <summary>
/// Gets the Url for a given node ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public HttpResponseMessage GetNiceUrl(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
return GetNiceUrl(guidUdi.Guid);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
/// <summary>
/// Gets the children for the content id passed in
/// </summary>
+31 -2
View File
@@ -46,7 +46,7 @@ namespace Umbraco.Web.Editors
//This is a special case, we'll accept a String here so that we can get page members when the special "all-members"
//id is passed in eventually we'll probably want to support GUID + Udi too
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetPagedChildren", "id", typeof(int), typeof(string)),
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetPath", "id", typeof(int), typeof(Guid), typeof(Udi)),
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetById", "id", typeof(int), typeof(Guid), typeof(Udi)),
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetByIds", "ids", typeof(int[]), typeof(Guid[]), typeof(Udi[]))));
}
@@ -153,7 +153,36 @@ namespace Umbraco.Web.Editors
return foundContent.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
}
/// <summary>
/// Gets the path for a given node ID
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <returns></returns>
public IEnumerable<int> GetPath(Guid id, UmbracoEntityTypes type)
{
var foundContent = GetResultForKey(id, type);
return foundContent.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
}
/// <summary>
/// Gets the path for a given node ID
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <returns></returns>
public IEnumerable<int> GetPath(Udi id, UmbracoEntityTypes type)
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
return GetPath(guidUdi.Guid, type);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
/// <summary>
/// Gets the url of an entity
/// </summary>
@@ -0,0 +1,43 @@
using Umbraco.Core;
using Umbraco.Core.Models;
namespace Umbraco.Web.Extensions
{
public static class UdiExtensions
{
/// <summary>
/// An extension method to easily acquire a typed version of content, media or member item for a given Udi
/// </summary>
/// <param name="udi"></param>
/// <returns>An <see cref="IPublishedContent"/> item if the item is a Document, Media or Member</returns>
public static IPublishedContent ToPublishedContent(this Udi udi)
{
Udi identifier;
if (Udi.TryParse(udi.ToString(), out identifier) == false)
return null;
var guidUdi = GuidUdi.Parse(udi.ToString());
var umbracoType = Constants.UdiEntityType.ToUmbracoObjectType(identifier.EntityType);
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var entityService = ApplicationContext.Current.Services.EntityService;
switch (umbracoType)
{
case UmbracoObjectTypes.Document:
return umbracoHelper.TypedContent(guidUdi.Guid);
case UmbracoObjectTypes.Media:
var mediaAttempt = entityService.GetIdForKey(guidUdi.Guid, umbracoType);
if (mediaAttempt.Success)
return umbracoHelper.TypedMedia(mediaAttempt.Result);
break;
case UmbracoObjectTypes.Member:
var memberAttempt = entityService.GetIdForKey(guidUdi.Guid, umbracoType);
if (memberAttempt.Success)
return umbracoHelper.TypedMember(memberAttempt.Result);
break;
}
return null;
}
}
}
@@ -1,4 +1,5 @@
using Newtonsoft.Json;
using Umbraco.Core.Models;
namespace Umbraco.Web.Models
{
@@ -14,5 +15,7 @@ namespace Umbraco.Web.Models
public bool IsInternal { get; set; }
[JsonProperty("type")]
public RelatedLinkType Type { get; set; }
[JsonIgnore]
public IPublishedContent Content { get; set; }
}
}
+10 -10
View File
@@ -12,16 +12,16 @@ namespace Umbraco.Web.Profiling
{
/// <summary>
/// A profiler used for web based activity based on the MiniProfiler framework
/// </summary>
/// </summary>
internal class WebProfiler : IProfiler
{
private const string BootRequestItemKey = "Umbraco.Web.Profiling.WebProfiler__isBootRequest";
private WebProfilerProvider _provider;
private readonly WebProfilerProvider _provider;
private int _first;
/// <summary>
/// Constructor
/// </summary>
/// </summary>
internal WebProfiler()
{
// create our own provider, which can provide a profiler even during boot
@@ -78,7 +78,7 @@ namespace Umbraco.Web.Profiling
{
// if this is the boot request, or if we should profile this request, stop
// (the boot request is always profiled, no matter what)
var isBootRequest = ((HttpApplication)sender).Context.Items[BootRequestItemKey] != null; // fixme perfs
var isBootRequest = ((HttpApplication)sender).Context.Items[BootRequestItemKey] != null;
if (isBootRequest)
_provider.EndBootRequest();
if (isBootRequest || ShouldProfile(sender))
@@ -87,11 +87,11 @@ namespace Umbraco.Web.Profiling
private bool ShouldProfile(object sender)
{
if (GlobalSettings.DebugMode == false)
if (GlobalSettings.DebugMode == false)
return false;
//will not run in medium trust
if (SystemUtilities.GetCurrentTrustLevel() < AspNetHostingPermissionLevel.High)
if (SystemUtilities.GetCurrentTrustLevel() < AspNetHostingPermissionLevel.High)
return false;
var request = TryGetRequest(sender);
@@ -109,7 +109,7 @@ namespace Umbraco.Web.Profiling
}
/// <summary>
/// Render the UI to display the profiler
/// Render the UI to display the profiler
/// </summary>
/// <returns></returns>
/// <remarks>
@@ -137,7 +137,7 @@ namespace Umbraco.Web.Profiling
/// Start the profiler
/// </summary>
public void Start()
{
{
MiniProfiler.Start();
}
@@ -145,7 +145,7 @@ namespace Umbraco.Web.Profiling
/// Start the profiler
/// </summary>
/// <remarks>
/// set discardResults to false when you want to abandon all profiling, this is useful for
/// set discardResults to false when you want to abandon all profiling, this is useful for
/// when someone is not authenticated or you want to clear the results based on some other mechanism.
/// </remarks>
public void Stop(bool discardResults = false)
@@ -26,7 +26,7 @@ namespace Umbraco.Web.PropertyEditors
/// <returns>The corresponding property value editor.</returns>
protected override PropertyValueEditor CreateValueEditor()
{
var baseEditor = base.CreateValueEditor();
var baseEditor = base.CreateValueEditor();
baseEditor.Validators.Add(new UploadFileTypeValidator());
return new FileUploadPropertyValueEditor(baseEditor, MediaFileSystem);
}
@@ -142,11 +142,11 @@ namespace Umbraco.Web.PropertyEditors
MediaFileSystem.UploadAutoFillProperties.Reset(content, autoFillConfig);
else
MediaFileSystem.UploadAutoFillProperties.Populate(content, autoFillConfig, MediaFileSystem.GetRelativePath(svalue));
}
}
}
/// <summary>
/// A custom pre-val editor to ensure that the data is stored how the legacy data was stored in
/// A custom pre-val editor to ensure that the data is stored how the legacy data was stored in
/// </summary>
internal class FileUploadPreValueEditor : ValueListPreValueEditor
{
@@ -197,7 +197,7 @@ namespace Umbraco.Web.PropertyEditors
{
var result = base.ConvertEditorToDb(editorValue, currentValue);
//this should just be a dictionary of values, we want to re-format this so that it is just one value in the dictionary that is
//this should just be a dictionary of values, we want to re-format this so that it is just one value in the dictionary that is
// semi-colon delimited
var values = result.Select(item => item.Value.Value).ToList();
@@ -231,7 +231,7 @@ namespace Umbraco.Web.PropertyEditors
{
//we'll make the server field the index number of the value so it can be wired up to the view
"item_" + index.ToInvariantString()
});
});
}
}
}
@@ -254,7 +254,7 @@ namespace Umbraco.Web.PropertyEditors
// even if the property has NOT been modified (it could be the same filename but
// a different file) - this is accepted (auto-fill props should die)
//
// FIXME
// TODO in v8:
// for some weird backward compatibility reasons,
// - media copy is not supported
// - auto-fill properties are not supported for content items
@@ -224,7 +224,7 @@ namespace Umbraco.Web.PropertyEditors
MediaFileSystem.UploadAutoFillProperties.Reset(content, autoFillConfig);
else
MediaFileSystem.UploadAutoFillProperties.Populate(content, autoFillConfig, MediaFileSystem.GetRelativePath(src));
}
}
}
internal class ImageCropperPreValueEditor : PreValueEditor
@@ -249,7 +249,7 @@ namespace Umbraco.Web.PropertyEditors
// even if the property has NOT been modified (it could be the same filename but
// a different file) - this is accepted (auto-fill props should die)
//
// FIXME
// TODO in v8:
// for some weird backward compatibility reasons,
// - media copy is not supported
// - auto-fill properties are not supported for content items
@@ -2,17 +2,10 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Media;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;
@@ -28,9 +21,9 @@ namespace Umbraco.Web.PropertyEditors
/// </summary>
internal class ImageCropperPropertyValueEditor : PropertyValueEditorWrapper
{
private MediaFileSystem _mediaFileSystem;
private readonly MediaFileSystem _mediaFileSystem;
public ImageCropperPropertyValueEditor(PropertyValueEditor wrapped, MediaFileSystem mediaFileSystem)
public ImageCropperPropertyValueEditor(PropertyValueEditor wrapped, MediaFileSystem mediaFileSystem)
: base(wrapped)
{
_mediaFileSystem = mediaFileSystem;
@@ -39,7 +32,7 @@ namespace Umbraco.Web.PropertyEditors
/// <summary>
/// This is called to merge in the prevalue crops with the value that is saved - similar to the property value converter for the front-end
/// </summary>
public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
{
var val = base.ConvertDbToEditor(property, propertyType, dataTypeService);
@@ -61,12 +54,8 @@ namespace Umbraco.Web.PropertyEditors
/// <returns>The converted value.</returns>
/// <remarks>
/// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para>
/// <para>FIXME this is ?!
/// This is value passed in from the editor. We normally don't care what the editorValue.Value is set to because
/// we are more interested in the files collection associated with it, however we do care about the value if we
/// are clearing files. By default the editorValue.Value will just be set to the name of the file (but again, we
/// just ignore this and deal with the file collection in editorValue.AdditionalData.ContainsKey("files") )
/// </para>
/// <para>editorValue.Value is used to figure out editorFile and, if it has been cleared, remove the old file - but
/// it is editorValue.AdditionalData["files"] that is used to determine the actual file that has been uploaded.</para>
/// </remarks>
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
{
@@ -179,8 +168,8 @@ namespace Umbraco.Web.PropertyEditors
return filepath;
}
public override string ConvertDbToString(Property property, PropertyType propertyType, Core.Services.IDataTypeService dataTypeService)
public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
{
if (property.Value == null || string.IsNullOrEmpty(property.Value.ToString()))
return null;
@@ -193,7 +182,7 @@ namespace Umbraco.Web.PropertyEditors
// more magic here ;-(
var config = dataTypeService.GetPreValuesByDataTypeId(propertyType.DataTypeDefinitionId).FirstOrDefault();
var crops = string.IsNullOrEmpty(config) ? "[]" : config;
var newVal = "{src: '" + val + "', crops: " + crops + "}";
var newVal = "{src: '" + val + "', crops: " + crops + "}";
return newVal;
}
}
@@ -16,6 +16,7 @@ using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web.Extensions;
namespace Umbraco.Web.PropertyEditors.ValueConverters
{
@@ -51,7 +52,8 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
{
if (UmbracoConfig.For.UmbracoSettings().Content.EnablePropertyValueConverters)
{
return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.ContentPickerAlias);
return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.ContentPickerAlias)
|| propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.ContentPicker2Alias);
}
return false;
}
@@ -75,10 +77,10 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
{
var attemptConvertInt = source.TryConvertTo<int>();
if (attemptConvertInt.Success)
{
return attemptConvertInt.Result;
}
var attemptConvertUdi = source.TryConvertTo<Udi>();
if (attemptConvertUdi.Success)
return attemptConvertUdi.Result;
return null;
}
@@ -108,11 +110,23 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
{
if ((propertyType.PropertyTypeAlias != null && PropertiesToExclude.Contains(propertyType.PropertyTypeAlias.ToLower(CultureInfo.InvariantCulture))) == false)
{
var content = UmbracoContext.Current.ContentCache.GetById((int)source);
return content;
IPublishedContent content;
if (source is int)
{
var sourceInt = (int)source;
content = UmbracoContext.Current.ContentCache.GetById(sourceInt);
if(content != null)
return content;
}
else
{
var sourceUdi = source as Udi;
content = sourceUdi.ToPublishedContent();
if (content != null)
return content;
}
}
}
return source;
}
@@ -135,6 +149,6 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
{
return source.ToString();
}
}
}
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@@ -12,6 +9,7 @@ using Umbraco.Core.Logging;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Web.Extensions;
namespace Umbraco.Web.PropertyEditors.ValueConverters
{
@@ -20,8 +18,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class LegacyRelatedLinksEditorValueConvertor : PropertyValueConverterBase
{
private static readonly string[] MatchingEditors = new string[]
{
private static readonly string[] MatchingEditors = {
Constants.PropertyEditors.RelatedLinksAlias,
Constants.PropertyEditors.RelatedLinks2Alias
};
@@ -65,11 +62,11 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
break;
case Constants.PropertyEditors.RelatedLinks2Alias:
var strLinkId = a.Value<string>("link");
var udiLinkId = strLinkId.TryConvertTo<GuidUdi>();
if (udiLinkId)
var udiAttempt = strLinkId.TryConvertTo<Udi>();
if (udiAttempt)
{
var udiLink = helper.UrlProvider.GetUrl(udiLinkId.Result.Guid);
a["link"] = udiLink;
var content = udiAttempt.Result.ToPublishedContent();
a["link"] = helper.NiceUrl(content.Id);
}
break;
}
@@ -103,8 +100,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
var d = new XmlDocument();
var e = d.CreateElement("links");
d.AppendChild(e);
var values = (IEnumerable<string>)source;
foreach (dynamic link in obj)
{
var ee = d.CreateElement("link");
@@ -8,11 +8,14 @@
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web.Extensions;
namespace Umbraco.Web.PropertyEditors.ValueConverters
{
@@ -20,12 +23,72 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
/// The media picker property value converter.
/// </summary>
[DefaultPropertyValueConverter]
[PropertyValueType(typeof(IPublishedContent))]
[PropertyValueCache(PropertyCacheValue.Object, PropertyCacheLevel.ContentCache)]
[PropertyValueCache(PropertyCacheValue.Source, PropertyCacheLevel.Content)]
[PropertyValueCache(PropertyCacheValue.XPath, PropertyCacheLevel.Content)]
public class MediaPickerPropertyConverter : PropertyValueConverterBase
public class MediaPickerPropertyConverter : PropertyValueConverterBase, IPropertyValueConverterMeta
{
public Type GetPropertyValueType(PublishedPropertyType propertyType)
{
return IsMultipleDataType(propertyType.DataTypeId) ? typeof(IEnumerable<IPublishedContent>) : typeof(IPublishedContent);
}
public PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType, PropertyCacheValue cacheValue)
{
PropertyCacheLevel returnLevel;
switch (cacheValue)
{
case PropertyCacheValue.Object:
returnLevel = PropertyCacheLevel.ContentCache;
break;
case PropertyCacheValue.Source:
returnLevel = PropertyCacheLevel.Content;
break;
case PropertyCacheValue.XPath:
returnLevel = PropertyCacheLevel.Content;
break;
default:
returnLevel = PropertyCacheLevel.None;
break;
}
return returnLevel;
}
/// <summary>
/// The is multiple data type.
/// </summary>
/// <param name="dataTypeId">
/// The data type id.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
private bool IsMultipleDataType(int dataTypeId)
{
var multipleItems = false;
try
{
var dts = ApplicationContext.Current.Services.DataTypeService;
var multiPickerPreValues =
dts.GetPreValuesCollectionByDataTypeId(dataTypeId).PreValuesAsDictionary;
var multiPickerPreValue = multiPickerPreValues.FirstOrDefault(x => string.Equals(x.Key, "multiPicker", StringComparison.InvariantCultureIgnoreCase)).Value;
var attemptConvert = multiPickerPreValue.Value.TryConvertTo<bool>();
if (attemptConvert.Success)
{
multipleItems = attemptConvert.Result;
}
}
catch (Exception ex)
{
LogHelper.Error<MediaPickerPropertyConverter>(string.Format("Error finding multipleItems data type prevalue on data type Id {0}", dataTypeId), ex);
}
return multipleItems;
}
/// <summary>
/// Checks if this converter can convert the property editor and registers if it can.
/// </summary>
@@ -37,10 +100,11 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
/// </returns>
public override bool IsConverter(PublishedPropertyType propertyType)
{
// ** Value converter disabled as not sure if we want to convert the legacy media picker or not **
return false;
// ** not sure if we want to convert the legacy media picker or not **
if (propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MediaPickerAlias))
return false;
//return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MediaPickerAlias);
return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MediaPicker2Alias);
}
/// <summary>
@@ -60,13 +124,11 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
/// </returns>
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
var attemptConvertInt = source.TryConvertTo<int>();
if (attemptConvertInt.Success)
{
return attemptConvertInt.Result;
}
return null;
var nodeIds = source.ToString()
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(Udi.Parse)
.ToArray();
return nodeIds;
}
/// <summary>
@@ -91,14 +153,27 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
return null;
}
if (UmbracoContext.Current != null)
var udis = (Udi[])source;
var mediaItems = new List<IPublishedContent>();
if (udis.Any())
{
return UmbracoContext.Current.MediaCache.GetById((int)source);
foreach (var udi in udis)
{
var item = udi.ToPublishedContent();
if (item != null)
mediaItems.Add(item);
}
if (IsMultipleDataType(propertyType.DataTypeId))
{
return mediaItems;
}
else
{
return mediaItems.FirstOrDefault();
}
}
return null;
return source;
}
}
}
@@ -1,9 +1,9 @@
using System;
using Umbraco.Core;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web.Extensions;
using Umbraco.Web.Security;
namespace Umbraco.Web.PropertyEditors.ValueConverters
@@ -19,17 +19,20 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
{
if (UmbracoConfig.For.UmbracoSettings().Content.EnablePropertyValueConverters)
{
return propertyType.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditors.MemberPickerAlias);
return propertyType.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditors.MemberPickerAlias)
|| propertyType.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditors.MemberPicker2Alias);
}
return false;
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
var intAttempt = source.TryConvertTo<int>();
if (intAttempt.Success)
return intAttempt.Result;
var attemptConvertInt = source.TryConvertTo<int>();
if (attemptConvertInt.Success)
return attemptConvertInt.Result;
var attemptConvertUdi = source.TryConvertTo<Udi>();
if (attemptConvertUdi.Success)
return attemptConvertUdi.Result;
return null;
}
@@ -40,11 +43,24 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
if (UmbracoContext.Current != null)
{
var membershipHelper = new MembershipHelper(UmbracoContext.Current);
return membershipHelper.GetById((int) source);
IPublishedContent member;
if (source is int)
{
var membershipHelper = new MembershipHelper(UmbracoContext.Current);
member = membershipHelper.GetById((int)source);
if (member != null)
return member;
}
else
{
var sourceUdi = source as Udi;
member = sourceUdi.ToPublishedContent();
if (member != null)
return member;
}
}
return null;
return source;
}
}
@@ -17,6 +17,7 @@ using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Web.Extensions;
namespace Umbraco.Web.PropertyEditors.ValueConverters
{
@@ -53,7 +54,8 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
{
if (UmbracoConfig.For.UmbracoSettings().Content.EnablePropertyValueConverters)
{
return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePickerAlias);
return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePickerAlias)
|| propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePicker2Alias);
}
return false;
}
@@ -75,13 +77,23 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
/// </returns>
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
var nodeIds =
source.ToString()
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
return nodeIds;
if (propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePickerAlias))
{
var nodeIds = source.ToString()
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
return nodeIds;
}
if (propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePicker2Alias))
{
var nodeIds = source.ToString()
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(Udi.Parse)
.ToArray();
return nodeIds;
}
return null;
}
/// <summary>
@@ -109,41 +121,67 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
//TODO: Inject an UmbracoHelper and create a GetUmbracoHelper method based on either injected or singleton
if (UmbracoContext.Current != null)
{
var nodeIds = (int[])source;
if ((propertyType.PropertyTypeAlias != null && PropertiesToExclude.InvariantContains(propertyType.PropertyTypeAlias)) == false)
if (propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePickerAlias))
{
var multiNodeTreePicker = new List<IPublishedContent>();
var nodeIds = (int[])source;
var umbHelper = new UmbracoHelper(UmbracoContext.Current);
if (nodeIds.Length > 0)
if ((propertyType.PropertyTypeAlias != null && PropertiesToExclude.InvariantContains(propertyType.PropertyTypeAlias)) == false)
{
var objectType = UmbracoObjectTypes.Unknown;
var multiNodeTreePicker = new List<IPublishedContent>();
foreach (var nodeId in nodeIds)
if (nodeIds.Length > 0)
{
var multiNodeTreePickerItem = GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Document, umbHelper.TypedContent)
?? GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Media, umbHelper.TypedMedia)
?? GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Member, umbHelper.TypedMember);
var umbHelper = new UmbracoHelper(UmbracoContext.Current);
if (multiNodeTreePickerItem != null)
var objectType = UmbracoObjectTypes.Unknown;
foreach (var nodeId in nodeIds)
{
multiNodeTreePicker.Add(multiNodeTreePickerItem);
var multiNodeTreePickerItem =
GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Document, umbHelper.TypedContent)
?? GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Media, umbHelper.TypedMedia)
?? GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Member, umbHelper.TypedMember);
if (multiNodeTreePickerItem != null)
{
multiNodeTreePicker.Add(multiNodeTreePickerItem);
}
}
}
//TODO: Get rid of this Yield thing
return multiNodeTreePicker.Yield().Where(x => x != null);
}
//TODO: Get rid of this Yield thing
return multiNodeTreePicker.Yield().Where(x => x != null);
// return the first nodeId as this is one of the excluded properties that expects a single id
return nodeIds.FirstOrDefault();
}
// return the first nodeId as this is one of the excluded properties that expects a single id
return nodeIds.FirstOrDefault();
}
else
{
return null;
if (propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePicker2Alias))
{
var udis = (Udi[])source;
if ((propertyType.PropertyTypeAlias != null && PropertiesToExclude.InvariantContains(propertyType.PropertyTypeAlias)) == false)
{
var multiNodeTreePicker = new List<IPublishedContent>();
if (udis.Length > 0)
{
foreach (var udi in udis)
{
var item = udi.ToPublishedContent();
if (item != null)
multiNodeTreePicker.Add(item);
}
}
//TODO: Get rid of this Yield thing
return multiNodeTreePicker.Yield().Where(x => x != null);
}
// return the first nodeId as this is one of the excluded properties that expects a single id
return udis.FirstOrDefault();
}
}
return source;
}
/// <summary>
@@ -16,6 +16,7 @@ using Umbraco.Core.Logging;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Web.Extensions;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
@@ -54,7 +55,8 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
{
if (UmbracoConfig.For.UmbracoSettings().Content.EnablePropertyValueConverters)
{
return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.RelatedLinksAlias);
return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.RelatedLinksAlias)
|| propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.RelatedLinks2Alias);
}
return false;
}
@@ -83,21 +85,41 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
var sourceString = source.ToString();
var relatedLinksData = JsonConvert.DeserializeObject<IEnumerable<RelatedLinkData>>(sourceString);
var relatedLinksData = JsonConvert.DeserializeObject<IEnumerable<RelatedLink>>(sourceString);
var relatedLinks = new List<RelatedLink>();
foreach (var linkData in relatedLinksData)
{
var relatedLink = new RelatedLink()
var relatedLink = new RelatedLink
{
Caption = linkData.Caption,
NewWindow = linkData.NewWindow,
IsInternal = linkData.IsInternal,
Type = linkData.Type,
Id = linkData.Internal,
Link = linkData.Link
};
relatedLink = CreateLink(relatedLink);
int contentId;
if (int.TryParse(relatedLink.Link, out contentId))
{
relatedLink.Id = contentId;
relatedLink = CreateLink(relatedLink);
}
else
{
var strLinkId = linkData.Link;
var udiAttempt = strLinkId.TryConvertTo<Udi>();
if (udiAttempt.Success)
{
var content = udiAttempt.Result.ToPublishedContent();
if (content != null)
{
relatedLink.Id = content.Id;
relatedLink = CreateLink(relatedLink);
relatedLink.Content = content;
}
}
}
if (relatedLink.IsDeleted == false)
{
@@ -138,17 +160,5 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
return link;
}
internal class RelatedLinkData : RelatedLinkBase
{
[JsonProperty("internal")]
public int? Internal { get; set; }
[JsonProperty("edit")]
public bool Edit { get; set; }
[JsonProperty("internalName")]
public string InternalName { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
}
}
}

Some files were not shown because too many files have changed in this diff Show More