Compare commits

...

16 Commits

Author SHA1 Message Date
Sebastiaan Janssen a91669abc0 Fixes unit tests 2016-02-17 13:28:11 +01:00
Shannon 3b9db8a92f tries fixing test for appveyor 2016-02-17 12:25:40 +01:00
Sebastiaan Janssen 1bfc1229bd Merge pull request #1134 from umbraco/temp-738-U4-7996
Upgrade SQL CE to hopefully fix SQL CE data loss bug
2016-02-17 11:54:25 +01:00
Sebastiaan Janssen 3d6fd2d785 Updates to SQL CE 4.0.0.1 2016-02-17 11:44:33 +01:00
Shannon e56881abc6 adds unit tests for new ext methods 2016-02-17 11:21:15 +01:00
Shannon d32991c30a re-organizing some namespaces for tests 2016-02-17 10:59:48 +01:00
Shannon 8758f9649b checks for null before assigning culture 2016-02-17 10:57:20 +01:00
Shannon 6f0f1ab2c3 fixes wrong constant used 2016-02-17 10:22:37 +01:00
Shannon cd28240172 Moves strings to constants, adds ControllerContextExtensions to get the UmbracoContext from the hierarchy of ControllerContext's, changes RenderModelBinder to use this method to get the UmbracoContext, changes UmbracoViewPageOfTModel to use this method to get the UmbracoContext, adds RouteDataExtensions to get the UmbracoContext from routedata, adds extension methods on the HttpContext to get the UmbracoContext from it.
Conflicts:
	src/Umbraco.Web/Mvc/RenderModelBinder.cs
2016-02-17 10:22:22 +01:00
Shannon 7002291c41 adds tests for ShouldAuthenticateRequest for app configurations 2016-02-16 14:51:15 +01:00
Shannon 51bbf7ceb5 U4-7494 Installation Fails for 7.3.3 - Intermittent - Value cannot be null. Parameter name: sqlSyntax 2016-02-16 14:22:59 +01:00
Shannon 82297a6ff1 U4-7929 Label datatype strips leading zeros 2016-02-16 13:23:37 +01:00
Shannon cc5ac1a84c bumps version 2016-02-16 11:57:10 +01:00
Shannon 6373add383 U4-7922 Preview is not working 2016-02-16 11:53:54 +01:00
Shannon 180099b718 U4-7890 XSLT Macro's not working - "Cannot use this obsoleted overload when the current provider" 2016-02-16 11:52:16 +01:00
Shannon 65f15125e1 U4-7939 - fix routes cache 2016-02-16 11:48:09 +01:00
61 changed files with 2057 additions and 1597 deletions
+2 -2
View File
@@ -175,8 +175,8 @@
<!-- Copy SQL CE -->
<ItemGroup>
<SQLCE4Files
Include="..\src\packages\SqlServerCE.4.0.0.0\**\*.*"
Exclude="..\src\packages\SqlServerCE.4.0.0.0\lib\**\*;..\src\packages\SqlServerCE.4.0.0.0\**\*.nu*"
Include="..\src\packages\SqlServerCE.4.0.0.1\**\*.*"
Exclude="..\src\packages\SqlServerCE.4.0.0.1\lib\**\*;..\src\packages\SqlServerCE.4.0.0.1\**\*.nu*"
/>
</ItemGroup>
+1 -1
View File
@@ -1,2 +1,2 @@
# Usage: on line 2 put the release version, on line 3 put the version comment (example: beta)
7.3.7
7.3.8
+8 -6
View File
@@ -47,13 +47,15 @@
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.dll</HintPath>
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="SqlServerCE" version="4.0.0.0" targetFramework="net40" />
<package id="SqlServerCE" version="4.0.0.1" targetFramework="net45" />
</packages>
+2 -2
View File
@@ -11,5 +11,5 @@ using System.Resources;
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("7.3.7")]
[assembly: AssemblyInformationalVersion("7.3.7")]
[assembly: AssemblyFileVersion("7.3.8")]
[assembly: AssemblyInformationalVersion("7.3.8")]
@@ -7,14 +7,22 @@ using Umbraco.Core.Models.EntityBase;
namespace Umbraco.Core.Cache
{
/// <summary>
/// Interface describing this cache provider as a wrapper for another
/// </summary>
internal interface IRuntimeCacheProviderWrapper
{
IRuntimeCacheProvider InnerProvider { get; }
}
/// <summary>
/// A wrapper for any IRuntimeCacheProvider that ensures that all inserts and returns
/// are a deep cloned copy of the item when the item is IDeepCloneable and that tracks changes are
/// reset if the object is TracksChangesEntityBase
/// </summary>
internal class DeepCloneRuntimeCacheProvider : IRuntimeCacheProvider
internal class DeepCloneRuntimeCacheProvider : IRuntimeCacheProvider, IRuntimeCacheProviderWrapper
{
internal IRuntimeCacheProvider InnerProvider { get; private set; }
public IRuntimeCacheProvider InnerProvider { get; private set; }
public DeepCloneRuntimeCacheProvider(IRuntimeCacheProvider innerProvider)
{
+19 -5
View File
@@ -290,7 +290,7 @@ namespace Umbraco.Core
TimeSpan timeout,
Func<TT> getCacheItem)
{
var cache = RuntimeCache as HttpRuntimeCacheProvider;
var cache = GetHttpRuntimeCacheProvider(RuntimeCache);
if (cache != null)
{
var result = cache.GetCacheItem(cacheKey, () => getCacheItem(), timeout, false, priority, refreshAction, cacheDependency);
@@ -314,7 +314,7 @@ namespace Umbraco.Core
CacheDependency cacheDependency,
Func<TT> getCacheItem)
{
var cache = RuntimeCache as HttpRuntimeCacheProvider;
var cache = GetHttpRuntimeCacheProvider(RuntimeCache);
if (cache != null)
{
var result = cache.GetCacheItem(cacheKey, () => getCacheItem(), null, false, priority, null, cacheDependency);
@@ -374,7 +374,7 @@ namespace Umbraco.Core
TimeSpan timeout,
Func<T> getCacheItem)
{
var cache = RuntimeCache as HttpRuntimeCacheProvider;
var cache = GetHttpRuntimeCacheProvider(RuntimeCache);
if (cache != null)
{
cache.InsertCacheItem(cacheKey, () => getCacheItem(), timeout, false, priority, null, cacheDependency);
@@ -400,7 +400,7 @@ namespace Umbraco.Core
TimeSpan? timeout,
Func<T> getCacheItem)
{
var cache = RuntimeCache as HttpRuntimeCacheProvider;
var cache = GetHttpRuntimeCacheProvider(RuntimeCache);
if (cache != null)
{
cache.InsertCacheItem(cacheKey, () => getCacheItem(), timeout, false, priority, refreshAction, cacheDependency);
@@ -409,6 +409,20 @@ namespace Umbraco.Core
}
#endregion
}
private HttpRuntimeCacheProvider GetHttpRuntimeCacheProvider(IRuntimeCacheProvider runtimeCache)
{
HttpRuntimeCacheProvider cache;
var wrapper = RuntimeCache as IRuntimeCacheProviderWrapper;
if (wrapper != null)
{
cache = wrapper.InnerProvider as HttpRuntimeCacheProvider;
}
else
{
cache = RuntimeCache as HttpRuntimeCacheProvider;
}
return cache;
}
}
}
@@ -6,7 +6,7 @@ namespace Umbraco.Core.Configuration
{
public class UmbracoVersion
{
private static readonly Version Version = new Version("7.3.7");
private static readonly Version Version = new Version("7.3.8");
/// <summary>
/// Gets the current version of Umbraco.
+6
View File
@@ -10,6 +10,12 @@ namespace Umbraco.Core
/// </summary>
public static class Web
{
public const string UmbracoContextDataToken = "umbraco-context";
public const string UmbracoDataToken = "umbraco";
public const string PublishedDocumentRequestDataToken = "umbraco-doc-request";
public const string CustomRouteDataToken = "umbraco-custom-route";
public const string UmbracoRouteDefinitionDataToken = "umbraco-route-def";
/// <summary>
/// The preview cookie name
/// </summary>
@@ -0,0 +1,28 @@
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Core.PropertyEditors.ValueConverters
{
/// <summary>
/// We need this property converter so that we always force the value of a label to be a string
/// </summary>
/// <remarks>
/// Without a property converter defined for the label type, the value will be converted with
/// the `ConvertUsingDarkMagic` method which will try to parse the value into it's correct type, but this
/// can cause issues if the string is detected as a number and then strips leading zeros.
/// Example: http://issues.umbraco.org/issue/U4-7929
/// </remarks>
[DefaultPropertyValueConverter]
[PropertyValueType(typeof (string))]
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class LabelValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
{
return Constants.PropertyEditors.NoEditAlias.Equals(propertyType.PropertyEditorAlias);
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
return source == null ? string.Empty : source.ToString();
}
}
}
+10
View File
@@ -41,6 +41,16 @@ namespace Umbraco.Core
ToCSharpEscapeChars[escape[0]] = escape[1];
}
/// <summary>
/// Removes new lines and tabs
/// </summary>
/// <param name="txt"></param>
/// <returns></returns>
internal static string StripWhitespace(this string txt)
{
return Regex.Replace(txt, @"\s", string.Empty);
}
internal static string StripFileExtension(this string fileName)
{
//filenames cannot contain line breaks
+5 -4
View File
@@ -102,13 +102,13 @@
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data.Entity" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.dll</HintPath>
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.dll</HintPath>
</Reference>
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
@@ -472,6 +472,7 @@
<Compile Include="Persistence\Repositories\TaskRepository.cs" />
<Compile Include="Persistence\Repositories\TaskTypeRepository.cs" />
<Compile Include="PropertyEditors\ValueConverters\GridValueConverter.cs" />
<Compile Include="PropertyEditors\ValueConverters\LabelValueConverter.cs" />
<Compile Include="Publishing\UnPublishedStatusType.cs" />
<Compile Include="Publishing\UnPublishStatus.cs" />
<Compile Include="Security\BackOfficeClaimsIdentityFactory.cs" />
+1 -1
View File
@@ -19,5 +19,5 @@
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="semver" version="1.1.2" targetFramework="net45" />
<package id="SharpZipLib" version="0.86.0" targetFramework="net4" />
<package id="SqlServerCE" version="4.0.0.0" targetFramework="net4" />
<package id="SqlServerCE" version="4.0.0.1" targetFramework="net45" />
</packages>
+1 -1
View File
@@ -72,7 +72,7 @@
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
@@ -42,7 +42,7 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 1; i < 11; i++)
{
Web.Cache.DistributedCache.Instance.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
global::Umbraco.Web.Cache.DistributedCache.Instance.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
}
Assert.AreEqual(10, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).IntIdsRefreshed.Count);
}
@@ -52,7 +52,7 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 0; i < 10; i++)
{
Web.Cache.DistributedCache.Instance.Refresh(
global::Umbraco.Web.Cache.DistributedCache.Instance.Refresh(
Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"),
x => x.Id,
new TestObjectWithId{Id = i});
@@ -65,7 +65,7 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 0; i < 11; i++)
{
Web.Cache.DistributedCache.Instance.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), Guid.NewGuid());
global::Umbraco.Web.Cache.DistributedCache.Instance.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), Guid.NewGuid());
}
Assert.AreEqual(11, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).GuidIdsRefreshed.Count);
}
@@ -75,7 +75,7 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 1; i < 13; i++)
{
Web.Cache.DistributedCache.Instance.Remove(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
global::Umbraco.Web.Cache.DistributedCache.Instance.Remove(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
}
Assert.AreEqual(12, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).IntIdsRemoved.Count);
}
@@ -85,7 +85,7 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 0; i < 13; i++)
{
Web.Cache.DistributedCache.Instance.RefreshAll(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"));
global::Umbraco.Web.Cache.DistributedCache.Instance.RefreshAll(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"));
}
Assert.AreEqual(13, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).CountOfFullRefreshes);
}
@@ -56,19 +56,19 @@ namespace Umbraco.Tests.Integration
ServiceContext.DomainService.Save(new UmbracoDomain("*100112") { DomainName = "*100112", RootContentId = c3.Id, LanguageId = l2.Id });
var content = c2;
var culture = Web.Models.ContentExtensions.GetCulture(null,
var culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null,
ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService,
content.Id, content.Path, new Uri("http://domain1.com/"));
Assert.AreEqual("en-US", culture.Name);
content = c2;
culture = Web.Models.ContentExtensions.GetCulture(null,
culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null,
ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService,
content.Id, content.Path, new Uri("http://domain1.fr/"));
Assert.AreEqual("fr-FR", culture.Name);
content = c4;
culture = Web.Models.ContentExtensions.GetCulture(null,
culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null,
ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService,
content.Id, content.Path, new Uri("http://domain1.fr/"));
Assert.AreEqual("de-DE", culture.Name);
@@ -380,7 +380,7 @@ namespace Umbraco.Tests.Routing
var content = umbracoContext.ContentCache.GetById(nodeId);
Assert.IsNotNull(content);
var culture = Web.Models.ContentExtensions.GetCulture(umbracoContext, domainService, ServiceContext.LocalizationService, null, content.Id, content.Path, new Uri(currentUrl));
var culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(umbracoContext, domainService, ServiceContext.LocalizationService, null, content.Id, content.Path, new Uri(currentUrl));
Assert.AreEqual(expectedCulture, culture.Name);
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
namespace Umbraco.Tests.Routing
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerFixture)]
[TestFixture]
public class RoutesCacheTests : BaseRoutingTest
{
[Test]
public void U4_7939()
{
//var routingContext = GetRoutingContext("/test", 1111);
var umbracoContext = GetUmbracoContext("/test", 0);
var cache = umbracoContext.ContentCache.InnerCache as PublishedContentCache;
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
PublishedContentCache.UnitTesting = false; // else does not write to routes cache
Assert.IsFalse(PublishedContentCache.UnitTesting);
var z = cache.GetByRoute(umbracoContext, false, "/home/sub1");
Assert.IsNotNull(z);
Assert.AreEqual(1173, z.Id);
var routes = cache.RoutesCache.GetCachedRoutes();
Assert.AreEqual(1, routes.Count);
// before the fix, the following assert would fail because the route would
// have been stored as { 0, "/home/sub1" } - essentially meaning we were NOT
// storing anything in the route cache!
Assert.AreEqual(1173, routes.Keys.First());
Assert.AreEqual("/home/sub1", routes.Values.First());
}
}
}
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using Microsoft.Owin;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Profiling;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
using Umbraco.Web.Security.Identity;
namespace Umbraco.Tests.Security
{
[TestFixture]
public class BackOfficeCookieManagerTests
{
[Test]
public void ShouldAuthenticateRequest_When_Not_Configured()
{
//should force app ctx to show not-configured
ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", "");
var dbCtx = new Mock<DatabaseContext>(Mock.Of<IDatabaseFactory>(), Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test");
dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(false);
var appCtx = new ApplicationContext(
dbCtx.Object,
MockHelper.GetMockedServiceContext(),
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var umbCtx = UmbracoContext.CreateContext(
Mock.Of<HttpContextBase>(),
appCtx,
new WebSecurity(Mock.Of<HttpContextBase>(), appCtx),
Mock.Of<IUmbracoSettingsSection>(), new List<IUrlProvider>(), false);
var mgr = new BackOfficeCookieManager(Mock.Of<IUmbracoContextAccessor>(accessor => accessor.Value == umbCtx));
var result = mgr.ShouldAuthenticateRequest(Mock.Of<IOwinContext>(), new Uri("http://localhost/umbraco"));
Assert.IsFalse(result);
}
[Test]
public void ShouldAuthenticateRequest_When_Configured()
{
var dbCtx = new Mock<DatabaseContext>(Mock.Of<IDatabaseFactory>(), Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test");
dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true);
var appCtx = new ApplicationContext(
dbCtx.Object,
MockHelper.GetMockedServiceContext(),
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var umbCtx = UmbracoContext.CreateContext(
Mock.Of<HttpContextBase>(),
appCtx,
new WebSecurity(Mock.Of<HttpContextBase>(), appCtx),
Mock.Of<IUmbracoSettingsSection>(), new List<IUrlProvider>(), false);
var mgr = new BackOfficeCookieManager(Mock.Of<IUmbracoContextAccessor>(accessor => accessor.Value == umbCtx));
var request = new Mock<OwinRequest>();
request.Setup(owinRequest => owinRequest.Uri).Returns(new Uri("http://localhost/umbraco"));
var result = mgr.ShouldAuthenticateRequest(
Mock.Of<IOwinContext>(context => context.Request == request.Object),
new Uri("http://localhost/umbraco"));
Assert.IsTrue(result);
}
//TODO : Write remaining tests for `ShouldAuthenticateRequest`
}
}
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
@@ -9,6 +8,7 @@ using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
namespace Umbraco.Tests.Security
{
+37 -21
View File
@@ -75,6 +75,10 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Lucene.Net.2.9.4.1\lib\net40\Lucene.Net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
@@ -94,6 +98,10 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\NUnit.2.6.2\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
<HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Semver">
<HintPath>..\packages\semver.1.1.2\lib\net45\Semver.dll</HintPath>
</Reference>
@@ -102,13 +110,13 @@
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Data.Entity.Design" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.dll</HintPath>
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.dll</HintPath>
</Reference>
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
@@ -167,10 +175,10 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AngularIntegration\AngularAntiForgeryTests.cs" />
<Compile Include="AngularIntegration\ContentModelSerializationTests.cs" />
<Compile Include="AngularIntegration\JsInitializationTests.cs" />
<Compile Include="AngularIntegration\ServerVariablesParserTests.cs" />
<Compile Include="Web\AngularIntegration\AngularAntiForgeryTests.cs" />
<Compile Include="Web\AngularIntegration\ContentModelSerializationTests.cs" />
<Compile Include="Web\AngularIntegration\JsInitializationTests.cs" />
<Compile Include="Web\AngularIntegration\ServerVariablesParserTests.cs" />
<Compile Include="ApplicationContextTests.cs" />
<Compile Include="AttemptTests.cs" />
<Compile Include="Cache\CacheRefresherTests.cs" />
@@ -179,12 +187,12 @@
<Compile Include="Cache\FullDataSetCachePolicyTests.cs" />
<Compile Include="Cache\SingleItemsOnlyCachePolicyTests.cs" />
<Compile Include="Collections\DeepCloneableListTests.cs" />
<Compile Include="Controllers\BackOfficeControllerUnitTests.cs" />
<Compile Include="Web\Controllers\BackOfficeControllerUnitTests.cs" />
<Compile Include="DelegateExtensionsTests.cs" />
<Compile Include="Logging\AsyncRollingFileAppenderTest.cs" />
<Compile Include="Logging\DebugAppender.cs" />
<Compile Include="Logging\ParallelForwarderTest.cs" />
<Compile Include="Mvc\RenderIndexActionSelectorAttributeTests.cs" />
<Compile Include="Web\Mvc\RenderIndexActionSelectorAttributeTests.cs" />
<Compile Include="Persistence\Repositories\AuditRepositoryTest.cs" />
<Compile Include="Persistence\Repositories\DomainRepositoryTest.cs" />
<Compile Include="Persistence\Repositories\PartialViewRepositoryTests.cs" />
@@ -192,7 +200,9 @@
<Compile Include="Persistence\Repositories\TaskRepositoryTest.cs" />
<Compile Include="Persistence\Repositories\TaskTypeRepositoryTest.cs" />
<Compile Include="Resolvers\ResolverBaseTest.cs" />
<Compile Include="Routing\RoutesCacheTests.cs" />
<Compile Include="Routing\UrlRoutingTestBase.cs" />
<Compile Include="Security\BackOfficeCookieManagerTests.cs" />
<Compile Include="Security\UmbracoBackOfficeIdentityTests.cs" />
<Compile Include="Services\PublicAccessServiceTests.cs" />
<Compile Include="StringNewlineExtensions.cs" />
@@ -232,8 +242,8 @@
<Compile Include="Models\UmbracoEntityTests.cs" />
<Compile Include="Models\UserTests.cs" />
<Compile Include="Models\UserTypeTests.cs" />
<Compile Include="Mvc\SurfaceControllerTests.cs" />
<Compile Include="Mvc\UmbracoViewPageTests.cs" />
<Compile Include="Web\Mvc\SurfaceControllerTests.cs" />
<Compile Include="Web\Mvc\UmbracoViewPageTests.cs" />
<Compile Include="BootManagers\CoreBootManagerTests.cs" />
<Compile Include="BootManagers\WebBootManagerTests.cs" />
<Compile Include="Cache\ObjectCacheProviderTests.cs" />
@@ -308,9 +318,9 @@
<Compile Include="Configurations\UmbracoSettings\ViewstateMoverModuleElementTests.cs" />
<Compile Include="Configurations\UmbracoSettings\WebRoutingElementDefaultTests.cs" />
<Compile Include="Configurations\UmbracoSettings\WebRoutingElementTests.cs" />
<Compile Include="Controllers\WebApiEditors\ContentControllerUnitTests.cs" />
<Compile Include="Controllers\WebApiEditors\FilterAllowedOutgoingContentAttributeTests.cs" />
<Compile Include="Controllers\WebApiEditors\MediaControllerUnitTests.cs" />
<Compile Include="Web\Controllers\WebApiEditors\ContentControllerUnitTests.cs" />
<Compile Include="Web\Controllers\WebApiEditors\FilterAllowedOutgoingContentAttributeTests.cs" />
<Compile Include="Web\Controllers\WebApiEditors\MediaControllerUnitTests.cs" />
<Compile Include="CoreXml\FrameworkXmlTests.cs" />
<Compile Include="DynamicsAndReflection\QueryableExtensionTests.cs" />
<Compile Include="DynamicsAndReflection\ExtensionMethodFinderTests.cs" />
@@ -320,8 +330,8 @@
<Compile Include="Migrations\Upgrades\ValidateV7UpgradeTest.cs" />
<Compile Include="Models\ContentExtensionsTests.cs" />
<Compile Include="Models\UserExtensionsTests.cs" />
<Compile Include="Mvc\MergeParentContextViewDataAttributeTests.cs" />
<Compile Include="Mvc\ViewDataDictionaryExtensionTests.cs" />
<Compile Include="Web\Mvc\MergeParentContextViewDataAttributeTests.cs" />
<Compile Include="Web\Mvc\ViewDataDictionaryExtensionTests.cs" />
<Compile Include="Persistence\PetaPocoExtensionsTest.cs" />
<Compile Include="Persistence\Querying\ContentTypeSqlMappingTests.cs" />
<Compile Include="Persistence\Repositories\MacroRepositoryTest.cs" />
@@ -417,7 +427,7 @@
<Compile Include="PublishedContent\PublishedContentTests.cs" />
<Compile Include="PublishedContent\PublishedMediaTests.cs" />
<Compile Include="HashCodeCombinerTests.cs" />
<Compile Include="Mvc\HtmlHelperExtensionMethodsTests.cs" />
<Compile Include="Web\Mvc\HtmlHelperExtensionMethodsTests.cs" />
<Compile Include="IO\IOHelperTest.cs" />
<Compile Include="LibraryTests.cs" />
<Compile Include="PropertyEditors\PropertyEditorValueConverterTests.cs" />
@@ -502,7 +512,7 @@
<DependentUpon>ImportResources.resx</DependentUpon>
</Compile>
<Compile Include="Services\ThreadSafetyServiceTest.cs" />
<Compile Include="Controllers\PluginControllerAreaTests.cs" />
<Compile Include="Web\Controllers\PluginControllerAreaTests.cs" />
<Compile Include="Cache\DistributedCache\DistributedCacheTests.cs" />
<Compile Include="Templates\MasterPageHelperTests.cs" />
<Compile Include="TestHelpers\BaseDatabaseFactoryTest.cs" />
@@ -566,6 +576,7 @@
<Compile Include="Plugins\TypeFinderTests.cs" />
<Compile Include="Routing\UmbracoModuleTests.cs" />
<Compile Include="VersionExtensionTests.cs" />
<Compile Include="Web\WebExtensionMethodTests.cs" />
<Compile Include="XmlExtensionsTests.cs" />
<Compile Include="XmlHelperTests.cs" />
</ItemGroup>
@@ -735,8 +746,13 @@
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.0\amd64\*.* "$(TargetDir)amd64\" /Y /F /E /D
xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.0\x86\*.* "$(TargetDir)x86\" /Y /F /E /D</PostBuildEvent>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<PropertyGroup>
<PreBuildEvent>xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\amd64\*.* "$(TargetDir)amd64\" /Y /F /E /I /C /D
xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" /Y /F /E /I /C /D</PreBuildEvent>
</PropertyGroup>
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
@@ -1,20 +1,11 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.IO;
using System.Net;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using NUnit.Framework;
using Umbraco.Core.Security;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.WebApi.Filters;
namespace Umbraco.Tests.AngularIntegration
namespace Umbraco.Tests.Web.AngularIntegration
{
[TestFixture]
public class AngularAntiForgeryTests
@@ -1,80 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core;
using Umbraco.Web.Models.ContentEditing;
namespace Umbraco.Tests.AngularIntegration
{
[TestFixture]
public class ContentModelSerializationTests
{
[Test]
public void Content_Display_To_Json()
{
//create 3 tabs with 3 properties each
var tabs = new List<Tab<ContentPropertyDisplay>>();
for (var tabIndex = 0; tabIndex < 3; tabIndex ++)
{
var props = new List<ContentPropertyDisplay>();
for (var propertyIndex = 0; propertyIndex < 3; propertyIndex ++)
{
props.Add(new ContentPropertyDisplay
{
Alias = "property" + propertyIndex,
Label = "Property " + propertyIndex,
Id = propertyIndex,
Value = "value" + propertyIndex,
Config = new Dictionary<string, object> {{ propertyIndex.ToInvariantString(), "value" }},
Description = "Description " + propertyIndex,
View = "~/Views/View" + propertyIndex,
HideLabel = false
});
}
tabs.Add(new Tab<ContentPropertyDisplay>()
{
Alias = "Tab" + tabIndex,
Label = "Tab" + tabIndex,
Properties = props
});
}
var displayModel = new ContentItemDisplay
{
Id = 1234,
Name = "Test",
Tabs = tabs
};
var json = JsonConvert.SerializeObject(displayModel);
var jObject = JObject.Parse(json);
Assert.AreEqual("1234", jObject["id"].ToString());
Assert.AreEqual("Test", jObject["name"].ToString());
Assert.AreEqual(3, jObject["tabs"].Count());
for (var tab = 0; tab < jObject["tabs"].Count(); tab++)
{
Assert.AreEqual("Tab" + tab, jObject["tabs"][tab]["alias"].ToString());
Assert.AreEqual("Tab" + tab, jObject["tabs"][tab]["label"].ToString());
Assert.AreEqual(3, jObject["tabs"][tab]["properties"].Count());
for (var prop = 0; prop < jObject["tabs"][tab]["properties"].Count(); prop++)
{
Assert.AreEqual("property" + prop, jObject["tabs"][tab]["properties"][prop]["alias"].ToString());
Assert.AreEqual("Property " + prop, jObject["tabs"][tab]["properties"][prop]["label"].ToString());
Assert.AreEqual(prop, jObject["tabs"][tab]["properties"][prop]["id"].Value<int>());
Assert.AreEqual("value" + prop, jObject["tabs"][tab]["properties"][prop]["value"].ToString());
Assert.AreEqual("{\"" + prop + "\":\"value\"}", jObject["tabs"][tab]["properties"][prop]["config"].ToString(Formatting.None));
Assert.AreEqual("Description " + prop, jObject["tabs"][tab]["properties"][prop]["description"].ToString());
Assert.AreEqual(false, jObject["tabs"][tab]["properties"][prop]["hideLabel"].Value<bool>());
}
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Web.Models.ContentEditing;
namespace Umbraco.Tests.Web.AngularIntegration
{
[TestFixture]
public class ContentModelSerializationTests
{
[Test]
public void Content_Display_To_Json()
{
//create 3 tabs with 3 properties each
var tabs = new List<Tab<ContentPropertyDisplay>>();
for (var tabIndex = 0; tabIndex < 3; tabIndex ++)
{
var props = new List<ContentPropertyDisplay>();
for (var propertyIndex = 0; propertyIndex < 3; propertyIndex ++)
{
props.Add(new ContentPropertyDisplay
{
Alias = "property" + propertyIndex,
Label = "Property " + propertyIndex,
Id = propertyIndex,
Value = "value" + propertyIndex,
Config = new Dictionary<string, object> {{ propertyIndex.ToInvariantString(), "value" }},
Description = "Description " + propertyIndex,
View = "~/Views/View" + propertyIndex,
HideLabel = false
});
}
tabs.Add(new Tab<ContentPropertyDisplay>()
{
Alias = "Tab" + tabIndex,
Label = "Tab" + tabIndex,
Properties = props
});
}
var displayModel = new ContentItemDisplay
{
Id = 1234,
Name = "Test",
Tabs = tabs
};
var json = JsonConvert.SerializeObject(displayModel);
var jObject = JObject.Parse(json);
Assert.AreEqual("1234", jObject["id"].ToString());
Assert.AreEqual("Test", jObject["name"].ToString());
Assert.AreEqual(3, jObject["tabs"].Count());
for (var tab = 0; tab < jObject["tabs"].Count(); tab++)
{
Assert.AreEqual("Tab" + tab, jObject["tabs"][tab]["alias"].ToString());
Assert.AreEqual("Tab" + tab, jObject["tabs"][tab]["label"].ToString());
Assert.AreEqual(3, jObject["tabs"][tab]["properties"].Count());
for (var prop = 0; prop < jObject["tabs"][tab]["properties"].Count(); prop++)
{
Assert.AreEqual("property" + prop, jObject["tabs"][tab]["properties"][prop]["alias"].ToString());
Assert.AreEqual("Property " + prop, jObject["tabs"][tab]["properties"][prop]["label"].ToString());
Assert.AreEqual(prop, jObject["tabs"][tab]["properties"][prop]["id"].Value<int>());
Assert.AreEqual("value" + prop, jObject["tabs"][tab]["properties"][prop]["value"].ToString());
Assert.AreEqual("{\"" + prop + "\":\"value\"}", jObject["tabs"][tab]["properties"][prop]["config"].ToString(Formatting.None));
Assert.AreEqual("Description " + prop, jObject["tabs"][tab]["properties"][prop]["description"].ToString());
Assert.AreEqual(false, jObject["tabs"][tab]["properties"][prop]["hideLabel"].Value<bool>());
}
}
}
}
}
@@ -1,41 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Manifest;
using Umbraco.Web.UI.JavaScript;
namespace Umbraco.Tests.AngularIntegration
{
[TestFixture]
public class JsInitializationTests
{
[Test]
public void Get_Default_Init()
{
var init = JsInitialization.GetDefaultInitialization();
Assert.IsTrue(init.Any());
}
[Test]
public void Parse_Main()
{
var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" });
Assert.AreEqual(@"LazyLoad.js([World], function () {
//we need to set the legacy UmbClientMgr path
UmbClientMgr.setUmbracoPath('Hello');
jQuery(document).ready(function () {
angular.bootstrap(document, ['umbraco']);
});
});", result);
}
}
}
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Web.UI.JavaScript;
namespace Umbraco.Tests.Web.AngularIntegration
{
[TestFixture]
public class JsInitializationTests
{
[Test]
public void Get_Default_Init()
{
var init = JsInitialization.GetDefaultInitialization();
Assert.IsTrue(init.Any());
}
[Test]
public void Parse_Main()
{
var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" });
Assert.AreEqual(@"LazyLoad.js([World], function () {
//we need to set the legacy UmbClientMgr path
UmbClientMgr.setUmbracoPath('Hello');
jQuery(document).ready(function () {
angular.bootstrap(document, ['umbraco']);
});
});".StripWhitespace(), result.StripWhitespace());
}
}
}
@@ -1,33 +1,34 @@
using System.Collections.Generic;
using NUnit.Framework;
using Umbraco.Web.UI.JavaScript;
namespace Umbraco.Tests.AngularIntegration
{
[TestFixture]
public class ServerVariablesParserTests
{
[Test]
public void Parse()
{
var d = new Dictionary<string, object>();
d.Add("test1", "Test 1");
d.Add("test2", "Test 2");
d.Add("test3", "Test 3");
d.Add("test4", "Test 4");
d.Add("test5", "Test 5");
var output = ServerVariablesParser.Parse(d);
Assert.IsTrue(output.Contains(@"Umbraco.Sys.ServerVariables = {
""test1"": ""Test 1"",
""test2"": ""Test 2"",
""test3"": ""Test 3"",
""test4"": ""Test 4"",
""test5"": ""Test 5""
} ;"));
}
}
using System.Collections.Generic;
using NUnit.Framework;
using Umbraco.Web.UI.JavaScript;
using Umbraco.Core;
namespace Umbraco.Tests.Web.AngularIntegration
{
[TestFixture]
public class ServerVariablesParserTests
{
[Test]
public void Parse()
{
var d = new Dictionary<string, object>();
d.Add("test1", "Test 1");
d.Add("test2", "Test 2");
d.Add("test3", "Test 3");
d.Add("test4", "Test 4");
d.Add("test5", "Test 5");
var output = ServerVariablesParser.Parse(d).StripWhitespace();
Assert.IsTrue(output.Contains(@"Umbraco.Sys.ServerVariables = {
""test1"": ""Test 1"",
""test2"": ""Test 2"",
""test3"": ""Test 3"",
""test4"": ""Test 4"",
""test5"": ""Test 5""
} ;".StripWhitespace()));
}
}
}
@@ -2,7 +2,7 @@
using NUnit.Framework;
using Umbraco.Web.Editors;
namespace Umbraco.Tests.Controllers
namespace Umbraco.Tests.Web.Controllers
{
[TestFixture]
public class BackOfficeControllerUnitTests
@@ -4,7 +4,7 @@ using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.Mvc;
namespace Umbraco.Tests.Controllers
namespace Umbraco.Tests.Web.Controllers
{
[TestFixture]
public class PluginControllerAreaTests : BaseWebTest
@@ -1,366 +1,366 @@
using System.Collections.Generic;
using System.Web.Http;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Web.Editors;
namespace Umbraco.Tests.Controllers.WebApiEditors
{
[TestFixture]
public class ContentControllerUnitTests
{
[Test]
public void Access_Allowed_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, contentService, 1234);
//assert
Assert.IsTrue(result);
}
[Test]
public void Throws_Exception_When_No_Content_Found()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(0)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>();
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act/assert
Assert.Throws<HttpResponseException>(() => ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F' }));
}
[Test]
public void No_Access_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(9876);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>();
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F'});
//assert
Assert.IsFalse(result);
}
[Test]
public void No_Access_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A", "B", "C" })
};
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F'});
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_Allowed_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A", "F", "C" })
};
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F'});
//assert
Assert.IsTrue(result);
}
[Test]
public void Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -1);
//assert
Assert.IsTrue(result);
}
[Test]
public void Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -20);
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(1234);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -20);
//assert
Assert.IsFalse(result);
}
[Test]
public void No_Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(1234);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -1);
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Root_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -1)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -1, new[] { 'A'});
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Root_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -1)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -1, new[] { 'B'});
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Recycle_Bin_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -20)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -20, new[] { 'A'});
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Recycle_Bin_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -20)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -20, new[] { 'B'});
//assert
Assert.IsFalse(result);
}
}
//NOTE: The below self hosted stuff does work so need to get some tests written. Some are not possible atm because
// of the legacy SQL calls like checking permissions.
//[TestFixture]
//public class ContentControllerHostedTests : BaseRoutingTest
//{
// protected override DatabaseBehavior DatabaseTestBehavior
// {
// get { return DatabaseBehavior.NoDatabasePerFixture; }
// }
// public override void TearDown()
// {
// base.TearDown();
// UmbracoAuthorizeAttribute.Enable = true;
// UmbracoApplicationAuthorizeAttribute.Enable = true;
// }
// /// <summary>
// /// Tests to ensure that the response filter works so that any items the user
// /// doesn't have access to are removed
// /// </summary>
// [Test]
// public async void Get_By_Ids_Response_Filtered()
// {
// UmbracoAuthorizeAttribute.Enable = false;
// UmbracoApplicationAuthorizeAttribute.Enable = false;
// var baseUrl = string.Format("http://{0}:9876", Environment.MachineName);
// var url = baseUrl + "/api/Content/GetByIds?ids=1&ids=2";
// var routingCtx = GetRoutingContext(url, 1234, null, true);
// var config = new HttpSelfHostConfiguration(baseUrl);
// using (var server = new HttpSelfHostServer(config))
// {
// var route = config.Routes.MapHttpRoute("test", "api/Content/GetByIds",
// new
// {
// controller = "Content",
// action = "GetByIds",
// id = RouteParameter.Optional
// });
// route.DataTokens["Namespaces"] = new string[] { "Umbraco.Web.Editors" };
// var client = new HttpClient(server);
// var request = new HttpRequestMessage
// {
// RequestUri = new Uri(url),
// Method = HttpMethod.Get
// };
// var result = await client.SendAsync(request);
// }
// }
//}
}
using System.Collections.Generic;
using System.Web.Http;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Web.Editors;
namespace Umbraco.Tests.Web.Controllers.WebApiEditors
{
[TestFixture]
public class ContentControllerUnitTests
{
[Test]
public void Access_Allowed_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, contentService, 1234);
//assert
Assert.IsTrue(result);
}
[Test]
public void Throws_Exception_When_No_Content_Found()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(0)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>();
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act/assert
Assert.Throws<HttpResponseException>(() => ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F' }));
}
[Test]
public void No_Access_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(9876);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>();
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F'});
//assert
Assert.IsFalse(result);
}
[Test]
public void No_Access_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A", "B", "C" })
};
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F'});
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_Allowed_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var contentMock = new Mock<IContent>();
contentMock.Setup(c => c.Path).Returns("-1,1234,5678");
var content = contentMock.Object;
var contentServiceMock = new Mock<IContentService>();
contentServiceMock.Setup(x => x.GetById(1234)).Returns(content);
var contentService = contentServiceMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A", "F", "C" })
};
userServiceMock.Setup(x => x.GetPermissions(user, 1234)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, contentService, 1234, new[] { 'F'});
//assert
Assert.IsTrue(result);
}
[Test]
public void Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -1);
//assert
Assert.IsTrue(result);
}
[Test]
public void Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -20);
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(1234);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -20);
//assert
Assert.IsFalse(result);
}
[Test]
public void No_Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(1234);
var user = userMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, null, null, -1);
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Root_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -1)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -1, new[] { 'A'});
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Root_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -1)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -1, new[] { 'B'});
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Recycle_Bin_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -20)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -20, new[] { 'A'});
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Recycle_Bin_By_Permission()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1234, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, -20)).Returns(permissions);
var userService = userServiceMock.Object;
//act
var result = ContentController.CheckPermissions(new Dictionary<string, object>(), user, userService, null, -20, new[] { 'B'});
//assert
Assert.IsFalse(result);
}
}
//NOTE: The below self hosted stuff does work so need to get some tests written. Some are not possible atm because
// of the legacy SQL calls like checking permissions.
//[TestFixture]
//public class ContentControllerHostedTests : BaseRoutingTest
//{
// protected override DatabaseBehavior DatabaseTestBehavior
// {
// get { return DatabaseBehavior.NoDatabasePerFixture; }
// }
// public override void TearDown()
// {
// base.TearDown();
// UmbracoAuthorizeAttribute.Enable = true;
// UmbracoApplicationAuthorizeAttribute.Enable = true;
// }
// /// <summary>
// /// Tests to ensure that the response filter works so that any items the user
// /// doesn't have access to are removed
// /// </summary>
// [Test]
// public async void Get_By_Ids_Response_Filtered()
// {
// UmbracoAuthorizeAttribute.Enable = false;
// UmbracoApplicationAuthorizeAttribute.Enable = false;
// var baseUrl = string.Format("http://{0}:9876", Environment.MachineName);
// var url = baseUrl + "/api/Content/GetByIds?ids=1&ids=2";
// var routingCtx = GetRoutingContext(url, 1234, null, true);
// var config = new HttpSelfHostConfiguration(baseUrl);
// using (var server = new HttpSelfHostServer(config))
// {
// var route = config.Routes.MapHttpRoute("test", "api/Content/GetByIds",
// new
// {
// controller = "Content",
// action = "GetByIds",
// id = RouteParameter.Optional
// });
// route.DataTokens["Namespaces"] = new string[] { "Umbraco.Web.Editors" };
// var client = new HttpClient(server);
// var request = new HttpRequestMessage
// {
// RequestUri = new Uri(url),
// Method = HttpMethod.Get
// };
// var result = await client.SendAsync(request);
// }
// }
//}
}
@@ -1,136 +1,136 @@
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.WebApi.Filters;
namespace Umbraco.Tests.Controllers.WebApiEditors
{
[TestFixture]
public class FilterAllowedOutgoingContentAttributeTests
{
[Test]
public void GetValueFromResponse_Already_EnumerableContent()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>));
var val = new List<ContentItemBasic>() {new ContentItemBasic()};
var result = att.GetValueFromResponse(
new ObjectContent(typeof (IEnumerable<ContentItemBasic>),
val,
new JsonMediaTypeFormatter(),
new MediaTypeHeaderValue("html/text")));
Assert.AreEqual(val, result);
Assert.AreEqual(1, ((IEnumerable<ContentItemBasic>)result).Count());
}
[Test]
public void GetValueFromResponse_From_Property()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>), "MyList");
var val = new List<ContentItemBasic>() { new ContentItemBasic() };
var container = new MyTestClass() {MyList = val};
var result = att.GetValueFromResponse(
new ObjectContent(typeof(MyTestClass),
container,
new JsonMediaTypeFormatter(),
new MediaTypeHeaderValue("html/text")));
Assert.AreEqual(val, result);
Assert.AreEqual(1, ((IEnumerable<ContentItemBasic>)result).Count());
}
[Test]
public void GetValueFromResponse_Returns_Null_Not_Found_Property()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>), "DontFind");
var val = new List<ContentItemBasic>() { new ContentItemBasic() };
var container = new MyTestClass() { MyList = val };
var result = att.GetValueFromResponse(
new ObjectContent(typeof(MyTestClass),
container,
new JsonMediaTypeFormatter(),
new MediaTypeHeaderValue("html/text")));
Assert.AreEqual(null, result);
}
[Test]
public void Filter_On_Start_Node()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>));
var list = new List<dynamic>();
var path = "";
for (var i = 0; i < 10; i++)
{
if (i > 0 && path.EndsWith(",") == false)
{
path += ",";
}
path += i.ToInvariantString();
list.Add(new ContentItemBasic { Id = i, Name = "Test" + i, ParentId = i, Path = path });
}
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(5);
var user = userMock.Object;
att.FilterBasedOnStartNode(list, user);
Assert.AreEqual(5, list.Count);
}
[Test]
public void Filter_On_Permissions()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>));
var list = new List<dynamic>();
for (var i = 0; i < 10; i++)
{
list.Add(new ContentItemBasic{Id = i, Name = "Test" + i, ParentId = -1});
}
var ids = list.Select(x => (int)x.Id).ToArray();
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
//we're only assigning 3 nodes browse permissions so that is what we expect as a result
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1, new string[]{ "F" }),
new EntityPermission(9, 2, new string[]{ "F" }),
new EntityPermission(9, 3, new string[]{ "F" }),
new EntityPermission(9, 4, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, ids)).Returns(permissions);
var userService = userServiceMock.Object;
att.FilterBasedOnPermissions(list, user, userService);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(1, list.ElementAt(0).Id);
Assert.AreEqual(2, list.ElementAt(1).Id);
Assert.AreEqual(3, list.ElementAt(2).Id);
}
private class MyTestClass
{
public IEnumerable<ContentItemBasic> MyList { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.WebApi.Filters;
namespace Umbraco.Tests.Web.Controllers.WebApiEditors
{
[TestFixture]
public class FilterAllowedOutgoingContentAttributeTests
{
[Test]
public void GetValueFromResponse_Already_EnumerableContent()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>));
var val = new List<ContentItemBasic>() {new ContentItemBasic()};
var result = att.GetValueFromResponse(
new ObjectContent(typeof (IEnumerable<ContentItemBasic>),
val,
new JsonMediaTypeFormatter(),
new MediaTypeHeaderValue("html/text")));
Assert.AreEqual(val, result);
Assert.AreEqual(1, ((IEnumerable<ContentItemBasic>)result).Count());
}
[Test]
public void GetValueFromResponse_From_Property()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>), "MyList");
var val = new List<ContentItemBasic>() { new ContentItemBasic() };
var container = new MyTestClass() {MyList = val};
var result = att.GetValueFromResponse(
new ObjectContent(typeof(MyTestClass),
container,
new JsonMediaTypeFormatter(),
new MediaTypeHeaderValue("html/text")));
Assert.AreEqual(val, result);
Assert.AreEqual(1, ((IEnumerable<ContentItemBasic>)result).Count());
}
[Test]
public void GetValueFromResponse_Returns_Null_Not_Found_Property()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>), "DontFind");
var val = new List<ContentItemBasic>() { new ContentItemBasic() };
var container = new MyTestClass() { MyList = val };
var result = att.GetValueFromResponse(
new ObjectContent(typeof(MyTestClass),
container,
new JsonMediaTypeFormatter(),
new MediaTypeHeaderValue("html/text")));
Assert.AreEqual(null, result);
}
[Test]
public void Filter_On_Start_Node()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>));
var list = new List<dynamic>();
var path = "";
for (var i = 0; i < 10; i++)
{
if (i > 0 && path.EndsWith(",") == false)
{
path += ",";
}
path += i.ToInvariantString();
list.Add(new ContentItemBasic { Id = i, Name = "Test" + i, ParentId = i, Path = path });
}
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(5);
var user = userMock.Object;
att.FilterBasedOnStartNode(list, user);
Assert.AreEqual(5, list.Count);
}
[Test]
public void Filter_On_Permissions()
{
var att = new FilterAllowedOutgoingContentAttribute(typeof(IEnumerable<ContentItemBasic>));
var list = new List<dynamic>();
for (var i = 0; i < 10; i++)
{
list.Add(new ContentItemBasic{Id = i, Name = "Test" + i, ParentId = -1});
}
var ids = list.Select(x => (int)x.Id).ToArray();
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartContentId).Returns(-1);
var user = userMock.Object;
var userServiceMock = new Mock<IUserService>();
//we're only assigning 3 nodes browse permissions so that is what we expect as a result
var permissions = new List<EntityPermission>
{
new EntityPermission(9, 1, new string[]{ "F" }),
new EntityPermission(9, 2, new string[]{ "F" }),
new EntityPermission(9, 3, new string[]{ "F" }),
new EntityPermission(9, 4, new string[]{ "A" })
};
userServiceMock.Setup(x => x.GetPermissions(user, ids)).Returns(permissions);
var userService = userServiceMock.Object;
att.FilterBasedOnPermissions(list, user, userService);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(1, list.ElementAt(0).Id);
Assert.AreEqual(2, list.ElementAt(1).Id);
Assert.AreEqual(3, list.ElementAt(2).Id);
}
private class MyTestClass
{
public IEnumerable<ContentItemBasic> MyList { get; set; }
}
}
}
@@ -1,142 +1,142 @@
using System.Collections.Generic;
using System.Web.Http;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Web.Editors;
namespace Umbraco.Tests.Controllers.WebApiEditors
{
[TestFixture]
public class MediaControllerUnitTests
{
[Test]
public void Access_Allowed_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
var mediaMock = new Mock<IMedia>();
mediaMock.Setup(m => m.Path).Returns("-1,1234,5678");
var media = mediaMock.Object;
var mediaServiceMock = new Mock<IMediaService>();
mediaServiceMock.Setup(x => x.GetById(1234)).Returns(media);
var mediaService = mediaServiceMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, mediaService, 1234);
//assert
Assert.IsTrue(result);
}
[Test]
public void Throws_Exception_When_No_Media_Found()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
var mediaMock = new Mock<IMedia>();
mediaMock.Setup(m => m.Path).Returns("-1,1234,5678");
var media = mediaMock.Object;
var mediaServiceMock = new Mock<IMediaService>();
mediaServiceMock.Setup(x => x.GetById(0)).Returns(media);
var mediaService = mediaServiceMock.Object;
//act/assert
Assert.Throws<HttpResponseException>(() => MediaController.CheckPermissions(new Dictionary<string, object>(), user, mediaService, 1234));
}
[Test]
public void No_Access_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartMediaId).Returns(9876);
var user = userMock.Object;
var mediaMock = new Mock<IMedia>();
mediaMock.Setup(m => m.Path).Returns("-1,1234,5678");
var media = mediaMock.Object;
var mediaServiceMock = new Mock<IMediaService>();
mediaServiceMock.Setup(x => x.GetById(1234)).Returns(media);
var mediaService = mediaServiceMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, mediaService, 1234);
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -1);
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(1234);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -1);
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -21);
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(1234);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -21);
//assert
Assert.IsFalse(result);
}
}
using System.Collections.Generic;
using System.Web.Http;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Web.Editors;
namespace Umbraco.Tests.Web.Controllers.WebApiEditors
{
[TestFixture]
public class MediaControllerUnitTests
{
[Test]
public void Access_Allowed_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
var mediaMock = new Mock<IMedia>();
mediaMock.Setup(m => m.Path).Returns("-1,1234,5678");
var media = mediaMock.Object;
var mediaServiceMock = new Mock<IMediaService>();
mediaServiceMock.Setup(x => x.GetById(1234)).Returns(media);
var mediaService = mediaServiceMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, mediaService, 1234);
//assert
Assert.IsTrue(result);
}
[Test]
public void Throws_Exception_When_No_Media_Found()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
var mediaMock = new Mock<IMedia>();
mediaMock.Setup(m => m.Path).Returns("-1,1234,5678");
var media = mediaMock.Object;
var mediaServiceMock = new Mock<IMediaService>();
mediaServiceMock.Setup(x => x.GetById(0)).Returns(media);
var mediaService = mediaServiceMock.Object;
//act/assert
Assert.Throws<HttpResponseException>(() => MediaController.CheckPermissions(new Dictionary<string, object>(), user, mediaService, 1234));
}
[Test]
public void No_Access_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(9);
userMock.Setup(u => u.StartMediaId).Returns(9876);
var user = userMock.Object;
var mediaMock = new Mock<IMedia>();
mediaMock.Setup(m => m.Path).Returns("-1,1234,5678");
var media = mediaMock.Object;
var mediaServiceMock = new Mock<IMediaService>();
mediaServiceMock.Setup(x => x.GetById(1234)).Returns(media);
var mediaService = mediaServiceMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, mediaService, 1234);
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -1);
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Root_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(1234);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -1);
//assert
Assert.IsFalse(result);
}
[Test]
public void Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(-1);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -21);
//assert
Assert.IsTrue(result);
}
[Test]
public void No_Access_To_Recycle_Bin_By_Path()
{
//arrange
var userMock = new Mock<IUser>();
userMock.Setup(u => u.Id).Returns(0);
userMock.Setup(u => u.StartMediaId).Returns(1234);
var user = userMock.Object;
//act
var result = MediaController.CheckPermissions(new Dictionary<string, object>(), user, null, -21);
//assert
Assert.IsFalse(result);
}
}
}
@@ -2,7 +2,7 @@ using System.Web.Mvc;
using NUnit.Framework;
using Umbraco.Web;
namespace Umbraco.Tests.Mvc
namespace Umbraco.Tests.Web.Mvc
{
[TestFixture]
public class HtmlHelperExtensionMethodsTests
@@ -1,86 +1,86 @@
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.Mvc;
namespace Umbraco.Tests.Mvc
{
[TestFixture]
public class MergeParentContextViewDataAttributeTests
{
[Test]
public void Ensure_All_Ancestor_ViewData_Is_Merged()
{
var http = new FakeHttpContextFactory("http://localhost");
//setup an heirarchy
var rootViewCtx = new ViewContext {Controller = new MyController(), RequestContext = http.RequestContext, ViewData = new ViewDataDictionary()};
var parentViewCtx = new ViewContext { Controller = new MyController(), RequestContext = http.RequestContext, RouteData = new RouteData(), ViewData = new ViewDataDictionary() };
parentViewCtx.RouteData.DataTokens.Add("ParentActionViewContext", rootViewCtx);
var controllerCtx = new ControllerContext(http.RequestContext, new MyController()) {RouteData = new RouteData()};
controllerCtx.RouteData.DataTokens.Add("ParentActionViewContext", parentViewCtx);
//set up the view data
controllerCtx.Controller.ViewData["Test1"] = "Test1";
controllerCtx.Controller.ViewData["Test2"] = "Test2";
controllerCtx.Controller.ViewData["Test3"] = "Test3";
parentViewCtx.ViewData["Test4"] = "Test4";
parentViewCtx.ViewData["Test5"] = "Test5";
parentViewCtx.ViewData["Test6"] = "Test6";
rootViewCtx.ViewData["Test7"] = "Test7";
rootViewCtx.ViewData["Test8"] = "Test8";
rootViewCtx.ViewData["Test9"] = "Test9";
var filter = new ResultExecutingContext(controllerCtx, new ContentResult()) {RouteData = controllerCtx.RouteData};
var att = new MergeParentContextViewDataAttribute();
Assert.IsTrue(filter.IsChildAction);
att.OnResultExecuting(filter);
Assert.AreEqual(9, controllerCtx.Controller.ViewData.Count);
}
[Test]
public void Ensure_All_Ancestor_ViewData_Is_Merged_Without_Data_Loss()
{
var http = new FakeHttpContextFactory("http://localhost");
//setup an heirarchy
var rootViewCtx = new ViewContext { Controller = new MyController(), RequestContext = http.RequestContext, ViewData = new ViewDataDictionary() };
var parentViewCtx = new ViewContext { Controller = new MyController(), RequestContext = http.RequestContext, RouteData = new RouteData(), ViewData = new ViewDataDictionary() };
parentViewCtx.RouteData.DataTokens.Add("ParentActionViewContext", rootViewCtx);
var controllerCtx = new ControllerContext(http.RequestContext, new MyController()) { RouteData = new RouteData() };
controllerCtx.RouteData.DataTokens.Add("ParentActionViewContext", parentViewCtx);
//set up the view data with overlapping keys
controllerCtx.Controller.ViewData["Test1"] = "Test1";
controllerCtx.Controller.ViewData["Test2"] = "Test2";
controllerCtx.Controller.ViewData["Test3"] = "Test3";
parentViewCtx.ViewData["Test2"] = "Test4";
parentViewCtx.ViewData["Test3"] = "Test5";
parentViewCtx.ViewData["Test4"] = "Test6";
rootViewCtx.ViewData["Test3"] = "Test7";
rootViewCtx.ViewData["Test4"] = "Test8";
rootViewCtx.ViewData["Test5"] = "Test9";
var filter = new ResultExecutingContext(controllerCtx, new ContentResult()) { RouteData = controllerCtx.RouteData };
var att = new MergeParentContextViewDataAttribute();
Assert.IsTrue(filter.IsChildAction);
att.OnResultExecuting(filter);
Assert.AreEqual(5, controllerCtx.Controller.ViewData.Count);
Assert.AreEqual("Test1", controllerCtx.Controller.ViewData["Test1"]);
Assert.AreEqual("Test2", controllerCtx.Controller.ViewData["Test2"]);
Assert.AreEqual("Test3", controllerCtx.Controller.ViewData["Test3"]);
Assert.AreEqual("Test6", controllerCtx.Controller.ViewData["Test4"]);
Assert.AreEqual("Test9", controllerCtx.Controller.ViewData["Test5"]);
}
internal class MyController : Controller
{
}
}
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.Mvc;
namespace Umbraco.Tests.Web.Mvc
{
[TestFixture]
public class MergeParentContextViewDataAttributeTests
{
[Test]
public void Ensure_All_Ancestor_ViewData_Is_Merged()
{
var http = new FakeHttpContextFactory("http://localhost");
//setup an heirarchy
var rootViewCtx = new ViewContext {Controller = new MyController(), RequestContext = http.RequestContext, ViewData = new ViewDataDictionary()};
var parentViewCtx = new ViewContext { Controller = new MyController(), RequestContext = http.RequestContext, RouteData = new RouteData(), ViewData = new ViewDataDictionary() };
parentViewCtx.RouteData.DataTokens.Add("ParentActionViewContext", rootViewCtx);
var controllerCtx = new ControllerContext(http.RequestContext, new MyController()) {RouteData = new RouteData()};
controllerCtx.RouteData.DataTokens.Add("ParentActionViewContext", parentViewCtx);
//set up the view data
controllerCtx.Controller.ViewData["Test1"] = "Test1";
controllerCtx.Controller.ViewData["Test2"] = "Test2";
controllerCtx.Controller.ViewData["Test3"] = "Test3";
parentViewCtx.ViewData["Test4"] = "Test4";
parentViewCtx.ViewData["Test5"] = "Test5";
parentViewCtx.ViewData["Test6"] = "Test6";
rootViewCtx.ViewData["Test7"] = "Test7";
rootViewCtx.ViewData["Test8"] = "Test8";
rootViewCtx.ViewData["Test9"] = "Test9";
var filter = new ResultExecutingContext(controllerCtx, new ContentResult()) {RouteData = controllerCtx.RouteData};
var att = new MergeParentContextViewDataAttribute();
Assert.IsTrue(filter.IsChildAction);
att.OnResultExecuting(filter);
Assert.AreEqual(9, controllerCtx.Controller.ViewData.Count);
}
[Test]
public void Ensure_All_Ancestor_ViewData_Is_Merged_Without_Data_Loss()
{
var http = new FakeHttpContextFactory("http://localhost");
//setup an heirarchy
var rootViewCtx = new ViewContext { Controller = new MyController(), RequestContext = http.RequestContext, ViewData = new ViewDataDictionary() };
var parentViewCtx = new ViewContext { Controller = new MyController(), RequestContext = http.RequestContext, RouteData = new RouteData(), ViewData = new ViewDataDictionary() };
parentViewCtx.RouteData.DataTokens.Add("ParentActionViewContext", rootViewCtx);
var controllerCtx = new ControllerContext(http.RequestContext, new MyController()) { RouteData = new RouteData() };
controllerCtx.RouteData.DataTokens.Add("ParentActionViewContext", parentViewCtx);
//set up the view data with overlapping keys
controllerCtx.Controller.ViewData["Test1"] = "Test1";
controllerCtx.Controller.ViewData["Test2"] = "Test2";
controllerCtx.Controller.ViewData["Test3"] = "Test3";
parentViewCtx.ViewData["Test2"] = "Test4";
parentViewCtx.ViewData["Test3"] = "Test5";
parentViewCtx.ViewData["Test4"] = "Test6";
rootViewCtx.ViewData["Test3"] = "Test7";
rootViewCtx.ViewData["Test4"] = "Test8";
rootViewCtx.ViewData["Test5"] = "Test9";
var filter = new ResultExecutingContext(controllerCtx, new ContentResult()) { RouteData = controllerCtx.RouteData };
var att = new MergeParentContextViewDataAttribute();
Assert.IsTrue(filter.IsChildAction);
att.OnResultExecuting(filter);
Assert.AreEqual(5, controllerCtx.Controller.ViewData.Count);
Assert.AreEqual("Test1", controllerCtx.Controller.ViewData["Test1"]);
Assert.AreEqual("Test2", controllerCtx.Controller.ViewData["Test2"]);
Assert.AreEqual("Test3", controllerCtx.Controller.ViewData["Test3"]);
Assert.AreEqual("Test6", controllerCtx.Controller.ViewData["Test4"]);
Assert.AreEqual("Test9", controllerCtx.Controller.ViewData["Test5"]);
}
internal class MyController : Controller
{
}
}
}
@@ -17,7 +17,7 @@ using Umbraco.Web.Mvc;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
namespace Umbraco.Tests.Mvc
namespace Umbraco.Tests.Web.Mvc
{
[TestFixture]
public class RenderIndexActionSelectorAttributeTests
@@ -1,5 +1,4 @@
using System;
using System.CodeDom;
using System.Linq;
using System.Web;
using System.Web.Mvc;
@@ -12,7 +11,6 @@ using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Profiling;
@@ -20,11 +18,10 @@ using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.Mvc;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
namespace Umbraco.Tests.Mvc
namespace Umbraco.Tests.Web.Mvc
{
[TestFixture]
public class SurfaceControllerTests
@@ -165,7 +162,7 @@ namespace Umbraco.Tests.Mvc
};
var routeData = new RouteData();
routeData.DataTokens.Add("umbraco-route-def", routeDefinition);
routeData.DataTokens.Add(Umbraco.Core.Constants.Web.UmbracoRouteDefinitionDataToken, routeDefinition);
var ctrl = new TestSurfaceController(umbCtx, new UmbracoHelper());
ctrl.ControllerContext = new ControllerContext(contextBase, routeData, ctrl);
@@ -1,42 +1,40 @@
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using NUnit.Framework;
using Umbraco.Web.Mvc;
namespace Umbraco.Tests.Mvc
{
[TestFixture]
public class ViewDataDictionaryExtensionTests
{
[Test]
public void Merge_View_Data()
{
var source = new ViewDataDictionary();
var dest = new ViewDataDictionary();
source.Add("Test1", "Test1");
dest.Add("Test2", "Test2");
dest.MergeViewDataFrom(source);
Assert.AreEqual(2, dest.Count);
}
[Test]
public void Merge_View_Data_Retains_Destination_Values()
{
var source = new ViewDataDictionary();
var dest = new ViewDataDictionary();
source.Add("Test1", "Test1");
dest.Add("Test1", "MyValue");
dest.Add("Test2", "Test2");
dest.MergeViewDataFrom(source);
Assert.AreEqual(2, dest.Count);
Assert.AreEqual("MyValue", dest["Test1"]);
Assert.AreEqual("Test2", dest["Test2"]);
}
}
}
using System.Web.Mvc;
using NUnit.Framework;
using Umbraco.Web.Mvc;
namespace Umbraco.Tests.Web.Mvc
{
[TestFixture]
public class ViewDataDictionaryExtensionTests
{
[Test]
public void Merge_View_Data()
{
var source = new ViewDataDictionary();
var dest = new ViewDataDictionary();
source.Add("Test1", "Test1");
dest.Add("Test2", "Test2");
dest.MergeViewDataFrom(source);
Assert.AreEqual(2, dest.Count);
}
[Test]
public void Merge_View_Data_Retains_Destination_Values()
{
var source = new ViewDataDictionary();
var dest = new ViewDataDictionary();
source.Add("Test1", "Test1");
dest.Add("Test1", "MyValue");
dest.Add("Test2", "Test2");
dest.MergeViewDataFrom(source);
Assert.AreEqual(2, dest.Count);
Assert.AreEqual("MyValue", dest["Test1"]);
Assert.AreEqual("Test2", dest["Test2"]);
}
}
}
@@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Profiling;
using Umbraco.Web;
using Umbraco.Web.Mvc;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
namespace Umbraco.Tests.Web
{
[TestFixture]
public class WebExtensionMethodTests
{
[Test]
public void UmbracoContextExtensions_GetUmbracoContext()
{
var appCtx = new ApplicationContext(
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var umbCtx = UmbracoContext.CreateContext(
Mock.Of<HttpContextBase>(),
appCtx,
new WebSecurity(Mock.Of<HttpContextBase>(), appCtx),
Mock.Of<IUmbracoSettingsSection>(),
new List<IUrlProvider>(),
false);
var items = new Dictionary<object, object>()
{
{UmbracoContext.HttpContextItemName, umbCtx}
};
var http = new Mock<HttpContextBase>();
http.Setup(x => x.Items).Returns(items);
var result = http.Object.GetUmbracoContext();
Assert.IsNotNull(result);
Assert.AreSame(umbCtx, result);
}
[Test]
public void RouteDataExtensions_GetUmbracoContext()
{
var appCtx = new ApplicationContext(
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var umbCtx = UmbracoContext.CreateContext(
Mock.Of<HttpContextBase>(),
appCtx,
new WebSecurity(Mock.Of<HttpContextBase>(), appCtx),
Mock.Of<IUmbracoSettingsSection>(),
new List<IUrlProvider>(),
false);
var r1 = new RouteData();
r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx);
var result = r1.GetUmbracoContext();
Assert.IsNotNull(result);
Assert.AreSame(umbCtx, result);
}
[Test]
public void ControllerContextExtensions_GetUmbracoContext_From_RouteValues()
{
var appCtx = new ApplicationContext(
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var umbCtx = UmbracoContext.CreateContext(
Mock.Of<HttpContextBase>(),
appCtx,
new WebSecurity(Mock.Of<HttpContextBase>(), appCtx),
Mock.Of<IUmbracoSettingsSection>(),
new List<IUrlProvider>(),
false);
var r1 = new RouteData();
r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx);
var ctx1 = CreateViewContext(new ControllerContext(Mock.Of<HttpContextBase>(), r1, new MyController()));
var r2 = new RouteData();
r2.DataTokens.Add("ParentActionViewContext", ctx1);
var ctx2 = CreateViewContext(new ControllerContext(Mock.Of<HttpContextBase>(), r2, new MyController()));
var r3 = new RouteData();
r3.DataTokens.Add("ParentActionViewContext", ctx2);
var ctx3 = CreateViewContext(new ControllerContext(Mock.Of<HttpContextBase>(), r3, new MyController()));
var result = ctx3.GetUmbracoContext();
Assert.IsNotNull(result);
Assert.AreSame(umbCtx, result);
}
[Test]
public void ControllerContextExtensions_GetUmbracoContext_From_HttpContext()
{
var appCtx = new ApplicationContext(
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var umbCtx = UmbracoContext.CreateContext(
Mock.Of<HttpContextBase>(),
appCtx,
new WebSecurity(Mock.Of<HttpContextBase>(), appCtx),
Mock.Of<IUmbracoSettingsSection>(),
new List<IUrlProvider>(),
false);
var items = new Dictionary<object, object>()
{
{UmbracoContext.HttpContextItemName, umbCtx}
};
var http = new Mock<HttpContextBase>();
http.Setup(x => x.Items).Returns(items);
var r1 = new RouteData();
var ctx1 = CreateViewContext(new ControllerContext(http.Object, r1, new MyController()));
var r2 = new RouteData();
r2.DataTokens.Add("ParentActionViewContext", ctx1);
var ctx2 = CreateViewContext(new ControllerContext(http.Object, r2, new MyController()));
var r3 = new RouteData();
r3.DataTokens.Add("ParentActionViewContext", ctx2);
var ctx3 = CreateViewContext(new ControllerContext(http.Object, r3, new MyController()));
var result = ctx3.GetUmbracoContext();
Assert.IsNotNull(result);
Assert.AreSame(umbCtx, result);
}
[Test]
public void ControllerContextExtensions_GetDataTokenInViewContextHierarchy()
{
var r1 = new RouteData();
r1.DataTokens.Add("hello", "world");
var ctx1 = CreateViewContext(new ControllerContext(Mock.Of<HttpContextBase>(), r1, new MyController()));
var r2 = new RouteData();
r2.DataTokens.Add("ParentActionViewContext", ctx1);
var ctx2 = CreateViewContext(new ControllerContext(Mock.Of<HttpContextBase>(), r2, new MyController()));
var r3 = new RouteData();
r3.DataTokens.Add("ParentActionViewContext", ctx2);
var ctx3 = CreateViewContext(new ControllerContext(Mock.Of<HttpContextBase>(), r3, new MyController()));
var result = ctx3.GetDataTokenInViewContextHierarchy("hello");
Assert.IsNotNull(result as string);
Assert.AreEqual((string)result, "world");
}
private ViewContext CreateViewContext(ControllerContext ctx)
{
return new ViewContext(ctx, Mock.Of<IView>(),
new ViewDataDictionary(), new TempDataDictionary(), new StringWriter());
}
private class MyController : Controller
{
}
}
}
+3 -1
View File
@@ -13,13 +13,15 @@
<package id="Microsoft.AspNet.WebApi.SelfHost" version="4.0.30506.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net45" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="MiniProfiler" version="2.1.0" targetFramework="net45" />
<package id="Moq" version="4.1.1309.0919" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
<package id="NUnit" version="2.6.2" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="Selenium.WebDriver" version="2.32.0" targetFramework="net45" />
<package id="semver" version="1.1.2" targetFramework="net45" />
<package id="SharpZipLib" version="0.86.0" targetFramework="net45" />
<package id="SqlServerCE" version="4.0.0.0" targetFramework="net45" />
<package id="SqlServerCE" version="4.0.0.1" targetFramework="net45" />
</packages>
+10 -12
View File
@@ -210,14 +210,12 @@
<Name>System.Data</Name>
</Reference>
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<HintPath>..\packages\SqlServerCE.4.0.0.0\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
<Reference Include="System.Data.SqlServerCe.Entity, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<HintPath>..\packages\SqlServerCE.4.0.0.1\lib\System.Data.SqlServerCe.Entity.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Drawing" />
@@ -2401,10 +2399,10 @@
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
<PostBuildEvent>xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.0\amd64\*.* "$(TargetDir)amd64\" /Y /F /E /D
xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.0\x86\*.* "$(TargetDir)x86\" /Y /F /E /D</PostBuildEvent>
<PreBuildEvent>xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\amd64\*.* "$(TargetDir)amd64\" /Y /F /E /I /C /D
xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" /Y /F /E /I /C /D</PreBuildEvent>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
@@ -2414,9 +2412,9 @@ xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.0\x86\*.* "$(TargetDir)x86\"
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>7360</DevelopmentServerPort>
<DevelopmentServerPort>7380</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:7370</IISUrl>
<IISUrl>http://localhost:7380</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
+1 -1
View File
@@ -31,6 +31,6 @@
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="SharpZipLib" version="0.86.0" targetFramework="net45" />
<package id="SqlServerCE" version="4.0.0.0" targetFramework="net45" />
<package id="SqlServerCE" version="4.0.0.1" targetFramework="net45" />
<package id="UrlRewritingNet.UrlRewriter" version="2.0.7" targetFramework="net45" />
</packages>
@@ -124,7 +124,7 @@ namespace Umbraco.Web.Macros
var routeVals = new RouteData();
routeVals.Values.Add("controller", "PartialViewMacro");
routeVals.Values.Add("action", "Index");
routeVals.DataTokens.Add("umbraco-context", umbCtx); //required for UmbracoViewPage
routeVals.DataTokens.Add(Umbraco.Core.Constants.Web.UmbracoContextDataToken, umbCtx); //required for UmbracoViewPage
//lets render this controller as a child action
var viewContext = new ViewContext {ViewData = new ViewDataDictionary()};;
@@ -110,7 +110,7 @@ namespace Umbraco.Web.Mvc
//match this area
controllerPluginRoute.DataTokens.Add("area", area.AreaName);
controllerPluginRoute.DataTokens.Add("umbraco", umbracoTokenValue); //ensure the umbraco token is set
controllerPluginRoute.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, umbracoTokenValue); //ensure the umbraco token is set
return controllerPluginRoute;
}
@@ -0,0 +1,50 @@
using System.Web.Mvc;
namespace Umbraco.Web.Mvc
{
public static class ControllerContextExtensions
{
/// <summary>
/// Tries to get the Umbraco context from the whole ControllerContext hierarchy based on data tokens and if that fails
/// it will attempt to fallback to retrieving it from the HttpContext.
/// </summary>
/// <param name="controllerContext"></param>
/// <returns></returns>
public static UmbracoContext GetUmbracoContext(this ControllerContext controllerContext)
{
var umbCtx = controllerContext.RouteData.GetUmbracoContext();
if (umbCtx != null) return umbCtx;
if (controllerContext.ParentActionViewContext != null)
{
//recurse
return controllerContext.ParentActionViewContext.GetUmbracoContext();
}
//fallback to getting from HttpContext
return controllerContext.HttpContext.GetUmbracoContext();
}
/// <summary>
/// Find a data token in the whole ControllerContext hierarchy of execution
/// </summary>
/// <param name="controllerContext"></param>
/// <param name="dataTokenName"></param>
/// <returns></returns>
internal static object GetDataTokenInViewContextHierarchy(this ControllerContext controllerContext, string dataTokenName)
{
if (controllerContext.RouteData.DataTokens.ContainsKey(dataTokenName))
{
return controllerContext.RouteData.DataTokens[dataTokenName];
}
if (controllerContext.ParentActionViewContext != null)
{
//recurse!
return controllerContext.ParentActionViewContext.GetDataTokenInViewContextHierarchy(dataTokenName);
}
return null;
}
}
}
+1 -17
View File
@@ -5,24 +5,8 @@ using System.Web.Mvc;
namespace Umbraco.Web.Mvc
{
internal static class ControllerExtensions
internal static class ControllerExtensions
{
internal static object GetDataTokenInViewContextHierarchy(this ControllerContext controllerContext, string dataTokenName)
{
if (controllerContext.RouteData.DataTokens.ContainsKey(dataTokenName))
{
return controllerContext.RouteData.DataTokens[dataTokenName];
}
if (controllerContext.ParentActionViewContext != null)
{
//recurse!
return controllerContext.ParentActionViewContext.GetDataTokenInViewContextHierarchy(dataTokenName);
}
return null;
}
/// <summary>
/// Return the controller name from the controller type
/// </summary>
+2 -2
View File
@@ -59,11 +59,11 @@ namespace Umbraco.Web.Mvc
{
if (_publishedContentRequest != null)
return _publishedContentRequest;
if (RouteData.DataTokens.ContainsKey("umbraco-doc-request") == false)
if (RouteData.DataTokens.ContainsKey(Core.Constants.Web.PublishedDocumentRequestDataToken) == false)
{
throw new InvalidOperationException("DataTokens must contain an 'umbraco-doc-request' key with a PublishedContentRequest object");
}
_publishedContentRequest = (PublishedContentRequest)RouteData.DataTokens["umbraco-doc-request"];
_publishedContentRequest = (PublishedContentRequest)RouteData.DataTokens[Core.Constants.Web.PublishedDocumentRequestDataToken];
return _publishedContentRequest;
}
}
+5 -5
View File
@@ -97,9 +97,9 @@ namespace Umbraco.Web.Mvc
internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add("umbraco", renderModel); //required for the RenderModelBinder and view engine
requestContext.RouteData.DataTokens.Add("umbraco-doc-request", docRequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add("umbraco-context", UmbracoContext); //required for UmbracoTemplatePage
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, renderModel); //required for the RenderModelBinder and view engine
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.PublishedDocumentRequestDataToken, docRequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, UmbracoContext); //required for UmbracoTemplatePage
}
private void UpdateRouteDataForRequest(RenderModel renderModel, RequestContext requestContext)
@@ -107,7 +107,7 @@ namespace Umbraco.Web.Mvc
if (renderModel == null) throw new ArgumentNullException("renderModel");
if (requestContext == null) throw new ArgumentNullException("requestContext");
requestContext.RouteData.DataTokens["umbraco"] = renderModel;
requestContext.RouteData.DataTokens[Core.Constants.Web.UmbracoDataToken] = renderModel;
// the rest should not change -- it's only the published content that has changed
}
@@ -337,7 +337,7 @@ namespace Umbraco.Web.Mvc
}
//store the route definition
requestContext.RouteData.DataTokens["umbraco-route-def"] = def;
requestContext.RouteData.DataTokens[Umbraco.Core.Constants.Web.UmbracoRouteDefinitionDataToken] = def;
return def;
}
+1 -1
View File
@@ -93,7 +93,7 @@ namespace Umbraco.Web.Mvc
/// <returns></returns>
private bool ShouldFindView(ControllerContext controllerContext, bool isPartial)
{
var umbracoToken = controllerContext.GetDataTokenInViewContextHierarchy("umbraco");
var umbracoToken = controllerContext.GetDataTokenInViewContextHierarchy(Core.Constants.Web.UmbracoDataToken);
//first check if we're rendering a partial view for the back office, or surface controller, etc...
//anything that is not IUmbracoRenderModel as this should only pertain to Umbraco views.
@@ -32,7 +32,7 @@ namespace Umbraco.Web.Mvc
public static object GetRequiredObject(this RouteValueDictionary items, string key)
{
if (key == null) throw new ArgumentNullException("key");
if (!items.Keys.Contains(key))
if (items.Keys.Contains(key) == false)
throw new ArgumentNullException("The " + key + " parameter was not found but is required");
return items[key];
}
+2 -2
View File
@@ -185,9 +185,9 @@ namespace Umbraco.Web.Mvc
while (currentContext != null)
{
var currentRouteData = currentContext.RouteData;
if (currentRouteData.DataTokens.ContainsKey("umbraco-route-def"))
if (currentRouteData.DataTokens.ContainsKey(Core.Constants.Web.UmbracoRouteDefinitionDataToken))
{
return Attempt.Succeed((RouteDefinition)currentRouteData.DataTokens["umbraco-route-def"]);
return Attempt.Succeed((RouteDefinition)currentRouteData.DataTokens[Core.Constants.Web.UmbracoRouteDefinitionDataToken]);
}
if (currentContext.IsChildAction)
{
@@ -24,7 +24,7 @@ namespace Umbraco.Web.Mvc
return false;
//ensure there is an umbraco token set
var umbracoToken = request.RouteData.DataTokens["umbraco"];
var umbracoToken = request.RouteData.DataTokens[Core.Constants.Web.UmbracoDataToken];
if (umbracoToken == null || string.IsNullOrWhiteSpace(umbracoToken.ToString()))
return false;
+2 -2
View File
@@ -34,7 +34,7 @@ namespace Umbraco.Web.Mvc
ValidateRouteData(context.RouteData);
var routeDef = (RouteDefinition)context.RouteData.DataTokens["umbraco-route-def"];
var routeDef = (RouteDefinition)context.RouteData.DataTokens[Umbraco.Core.Constants.Web.UmbracoRouteDefinitionDataToken];
//Special case, if it is webforms but we're posting to an MVC surface controller, then we
// need to return the webforms result instead
@@ -91,7 +91,7 @@ namespace Umbraco.Web.Mvc
/// </summary>
private static void ValidateRouteData(RouteData routeData)
{
if (routeData.DataTokens.ContainsKey("umbraco-route-def") == false)
if (routeData.DataTokens.ContainsKey(Umbraco.Core.Constants.Web.UmbracoRouteDefinitionDataToken) == false)
{
throw new InvalidOperationException("Can only use " + typeof(UmbracoPageResult).Name +
" in the context of an Http POST when using a SurfaceController form");
+18 -26
View File
@@ -1,4 +1,5 @@
using System;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.Mvc;
@@ -26,24 +27,13 @@ namespace Umbraco.Web.Mvc
get
{
//we should always try to return the context from the data tokens just in case its a custom context and not
//using the UmbracoContext.Current.
//we will fallback to the singleton if necessary.
if (ViewContext.RouteData.DataTokens.ContainsKey("umbraco-context"))
{
return (UmbracoContext)ViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-context");
}
//next check if it is a child action and see if the parent has it set in data tokens
if (ViewContext.IsChildAction)
{
if (ViewContext.ParentActionViewContext.RouteData.DataTokens.ContainsKey("umbraco-context"))
{
return (UmbracoContext)ViewContext.ParentActionViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-context");
}
}
//lastly, we will use the singleton, the only reason this should ever happen is is someone is rendering a page that inherits from this
//class and are rendering it outside of the normal Umbraco routing process. Very unlikely.
return UmbracoContext.Current;
//using the UmbracoContext.Current, we will fallback to the singleton if necessary.
var umbCtx = ViewContext.GetUmbracoContext()
//lastly, we will use the singleton, the only reason this should ever happen is is someone is rendering a page that inherits from this
//class and are rendering it outside of the normal Umbraco routing process. Very unlikely.
?? UmbracoContext.Current;
return umbCtx;
}
}
@@ -65,16 +55,16 @@ namespace Umbraco.Web.Mvc
//we should always try to return the object from the data tokens just in case its a custom object and not
//using the UmbracoContext.Current.
//we will fallback to the singleton if necessary.
if (ViewContext.RouteData.DataTokens.ContainsKey("umbraco-doc-request"))
if (ViewContext.RouteData.DataTokens.ContainsKey(Core.Constants.Web.PublishedDocumentRequestDataToken))
{
return (PublishedContentRequest)ViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-doc-request");
return (PublishedContentRequest)ViewContext.RouteData.DataTokens.GetRequiredObject(Core.Constants.Web.PublishedDocumentRequestDataToken);
}
//next check if it is a child action and see if the parent has it set in data tokens
if (ViewContext.IsChildAction)
{
if (ViewContext.ParentActionViewContext.RouteData.DataTokens.ContainsKey("umbraco-doc-request"))
if (ViewContext.ParentActionViewContext.RouteData.DataTokens.ContainsKey(Core.Constants.Web.PublishedDocumentRequestDataToken))
{
return (PublishedContentRequest)ViewContext.ParentActionViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-doc-request");
return (PublishedContentRequest)ViewContext.ParentActionViewContext.RouteData.DataTokens.GetRequiredObject(Core.Constants.Web.PublishedDocumentRequestDataToken);
}
}
@@ -178,10 +168,12 @@ namespace Umbraco.Web.Mvc
var ok = sourceContent != null;
if (sourceContent != null)
{
// try to grab the culture
// using context's culture by default
var culture = UmbracoContext.PublishedContentRequest.Culture;
{
// use context culture as default, if available
var culture = CultureInfo.CurrentCulture;
if (UmbracoContext.PublishedContentRequest != null && UmbracoContext.PublishedContentRequest.Culture != null)
culture = UmbracoContext.PublishedContentRequest.Culture;
var sourceRenderModel = source as RenderModel;
if (sourceRenderModel != null)
culture = sourceRenderModel.CurrentCulture;
@@ -3,6 +3,8 @@ using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
@@ -19,7 +21,8 @@ namespace Umbraco.Web.Mvc
if (found == null) return new NotFoundHandler();
umbracoContext.PublishedContentRequest = new PublishedContentRequest(
umbracoContext.CleanedUmbracoUrl, umbracoContext.RoutingContext)
umbracoContext.CleanedUmbracoUrl, umbracoContext.RoutingContext,
UmbracoConfig.For.UmbracoSettings().WebRouting, s => Roles.Provider.GetRolesForUser(s))
{
PublishedContent = found
};
@@ -31,11 +34,11 @@ namespace Umbraco.Web.Mvc
var renderModel = new RenderModel(umbracoContext.PublishedContentRequest.PublishedContent, umbracoContext.PublishedContentRequest.Culture);
//assigns the required tokens to the request
requestContext.RouteData.DataTokens.Add("umbraco", renderModel);
requestContext.RouteData.DataTokens.Add("umbraco-doc-request", umbracoContext.PublishedContentRequest);
requestContext.RouteData.DataTokens.Add("umbraco-context", umbracoContext);
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, renderModel);
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.PublishedDocumentRequestDataToken, umbracoContext.PublishedContentRequest);
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbracoContext);
//this is used just for a flag that this is an umbraco custom route
requestContext.RouteData.DataTokens.Add("umbraco-custom-route", true);
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.CustomRouteDataToken, true);
//Here we need to detect if a SurfaceController has posted
var formInfo = RenderRouteHandler.GetFormInfo(requestContext);
@@ -49,7 +52,7 @@ namespace Umbraco.Web.Mvc
};
//set the special data token to the current route definition
requestContext.RouteData.DataTokens["umbraco-route-def"] = def;
requestContext.RouteData.DataTokens[Umbraco.Core.Constants.Web.UmbracoRouteDefinitionDataToken] = def;
return RenderRouteHandler.HandlePostedValues(requestContext, formInfo);
}
@@ -57,12 +57,12 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache
if (content != null && preview == false)
{
var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/')));
var iscanon =
UnitTesting == false
var iscanon =
UnitTesting == false
&& DomainHelper.ExistsDomainInPath(umbracoContext.Application.Services.DomainService.GetAll(false), content.Path, domainRootNodeId) == false;
// and only if this is the canonical url (the one GetUrl would return)
if (iscanon)
_routesCache.Store(contentId, route);
_routesCache.Store(content.Id, route);
}
return content;
@@ -159,7 +159,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache
// we add this check - we look for the document matching "/" and if it's not us, then
// we do not hide the top level path
// it has to be taken care of in GetByRoute too so if
// "/foo" fails (looking for "/*/foo") we try also "/foo".
// "/foo" fails (looking for "/*/foo") we try also "/foo".
// this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but
// that's the way it works pre-4.10 and we try to be backward compat for the time being
if (node.Parent == null)
@@ -244,8 +244,8 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache
private static IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing)
{
return xmlNode == null
? null
return xmlNode == null
? null
: (new XmlPublishedContent(xmlNode, isPreviewing)).CreateModel();
}
@@ -398,7 +398,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache
if (startNodeId > 0)
{
// if in a domain then use the root node of the domain
xpath = string.Format(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId);
xpath = string.Format(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId);
}
else
{
@@ -409,7 +409,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache
// umbraco does not consistently guarantee that sortOrder starts with 0
// so the one that we want is the one with the smallest sortOrder
// read http://stackoverflow.com/questions/1128745/how-can-i-use-xpath-to-find-the-minimum-value-of-an-attribute-in-a-set-of-elemen
// so that one does not work, because min(@sortOrder) maybe 1
// xpath = "/root/*[@isDoc and @sortOrder='0']";
@@ -453,7 +453,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache
else
{
xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlName, part);
}
}
+28
View File
@@ -0,0 +1,28 @@
using System;
using System.Web.Routing;
namespace Umbraco.Web
{
public static class RouteDataExtensions
{
/// <summary>
/// Tries to get the Umbraco context from the DataTokens
/// </summary>
/// <param name="routeData"></param>
/// <returns></returns>
/// <remarks>
/// This is useful when working on async threads since the UmbracoContext is not copied over explicitly
/// </remarks>
public static UmbracoContext GetUmbracoContext(this RouteData routeData)
{
if (routeData == null) throw new ArgumentNullException("routeData");
if (routeData.DataTokens.ContainsKey(Core.Constants.Web.UmbracoContextDataToken))
{
var umbCtx = routeData.DataTokens[Core.Constants.Web.UmbracoContextDataToken] as UmbracoContext;
return umbCtx;
}
return null;
}
}
}
@@ -28,7 +28,7 @@ namespace Umbraco.Web.Routing
if (umbracoContext.HttpContext.Request.RequestContext == null) return null;
if (umbracoContext.HttpContext.Request.RequestContext.RouteData == null) return null;
if (umbracoContext.HttpContext.Request.RequestContext.RouteData.DataTokens == null) return null;
if (umbracoContext.HttpContext.Request.RequestContext.RouteData.DataTokens.ContainsKey("umbraco-custom-route") == false) return null;
if (umbracoContext.HttpContext.Request.RequestContext.RouteData.DataTokens.ContainsKey(Umbraco.Core.Constants.Web.CustomRouteDataToken) == false) return null;
//ok so it's a custom route with published content assigned, check if the id being requested for is the same id as the assigned published content
return id == umbracoContext.PublishedContentRequest.PublishedContent.Id
? umbracoContext.PublishedContentRequest.PublishedContent.Url
@@ -73,6 +73,16 @@ namespace Umbraco.Web.Security.Identity
/// </remarks>
internal bool ShouldAuthenticateRequest(IOwinContext ctx, Uri originalRequestUrl, bool checkForceAuthTokens = true)
{
if (_umbracoContextAccessor.Value.Application.IsConfigured == false
&& _umbracoContextAccessor.Value.Application.DatabaseContext.IsDatabaseConfigured == false)
{
//Do not authenticate the request if we don't have a db and we are not configured - since we will never need
// to know a current user in this scenario - we treat it as a new install. Without this we can have some issues
// when people have older invalid cookies on the same domain since our user managers might attempt to lookup a user
// and we don't even have a db.
return false;
}
var request = ctx.Request;
var httpCtx = ctx.TryGetHttpContext();
+2
View File
@@ -304,11 +304,13 @@
<Compile Include="Media\EmbedProviders\Flickr.cs" />
<Compile Include="Models\ContentEditing\SimpleNotificationModel.cs" />
<Compile Include="Models\PublishedContentWithKeyBase.cs" />
<Compile Include="Mvc\ControllerContextExtensions.cs" />
<Compile Include="Mvc\IRenderController.cs" />
<Compile Include="Mvc\RenderIndexActionSelectorAttribute.cs" />
<Compile Include="Mvc\ValidateMvcAngularAntiForgeryTokenAttribute.cs" />
<Compile Include="PropertyEditors\DatePreValueEditor.cs" />
<Compile Include="RequestLifespanMessagesFactory.cs" />
<Compile Include="RouteDataExtensions.cs" />
<Compile Include="Scheduling\LatchedBackgroundTaskBase.cs" />
<Compile Include="Security\Identity\ExternalSignInAutoLinkOptions.cs" />
<Compile Include="Security\Identity\FixWindowsAuthMiddlware.cs" />
+3 -3
View File
@@ -21,7 +21,7 @@ namespace Umbraco.Web
/// </summary>
public class UmbracoContext : DisposableObject, IDisposeOnRequestEnd
{
private const string HttpContextItemName = "Umbraco.Web.UmbracoContext";
internal const string HttpContextItemName = "Umbraco.Web.UmbracoContext";
private static readonly object Locker = new object();
private bool _replacing;
@@ -133,7 +133,7 @@ namespace Umbraco.Web
UmbracoContext.Current._replacing = true;
}
var umbracoContext = CreateContext(httpContext, applicationContext, webSecurity, umbracoSettings, urlProviders, preview ?? false);
var umbracoContext = CreateContext(httpContext, applicationContext, webSecurity, umbracoSettings, urlProviders, preview);
//assign the singleton
UmbracoContext.Current = umbracoContext;
@@ -158,7 +158,7 @@ namespace Umbraco.Web
WebSecurity webSecurity,
IUmbracoSettingsSection umbracoSettings,
IEnumerable<IUrlProvider> urlProviders,
bool preview)
bool? preview)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
@@ -2,6 +2,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Umbraco.Core;
using Umbraco.Core.Events;
namespace Umbraco.Web
@@ -11,6 +13,38 @@ namespace Umbraco.Web
/// </summary>
public static class UmbracoContextExtensions
{
/// <summary>
/// tries to get the Umbraco context from the HttpContext
/// </summary>
/// <param name="http"></param>
/// <returns></returns>
/// <remarks>
/// This is useful when working on async threads since the UmbracoContext is not copied over explicitly
/// </remarks>
public static UmbracoContext GetUmbracoContext(this HttpContext http)
{
return GetUmbracoContext(new HttpContextWrapper(http));
}
/// <summary>
/// tries to get the Umbraco context from the HttpContext
/// </summary>
/// <param name="http"></param>
/// <returns></returns>
/// <remarks>
/// This is useful when working on async threads since the UmbracoContext is not copied over explicitly
/// </remarks>
public static UmbracoContext GetUmbracoContext(this HttpContextBase http)
{
if (http == null) throw new ArgumentNullException("http");
if (http.Items.Contains(UmbracoContext.HttpContextItemName))
{
var umbCtx = http.Items[UmbracoContext.HttpContextItemName] as UmbracoContext;
return umbCtx;
}
return null;
}
/// <summary>
/// If there are event messages in the current request this will return them , otherwise it will return null
+2 -2
View File
@@ -336,7 +336,7 @@ namespace Umbraco.Web
{
route.DataTokens = new RouteValueDictionary();
}
route.DataTokens.Add("umbraco", "api"); //ensure the umbraco token is set
route.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, "api"); //ensure the umbraco token is set
}
private void RouteLocalSurfaceController(Type controller, string umbracoPath)
@@ -347,7 +347,7 @@ namespace Umbraco.Web
umbracoPath + "/Surface/" + meta.ControllerName + "/{action}/{id}",//url to match
new { controller = meta.ControllerName, action = "Index", id = UrlParameter.Optional },
new[] { meta.ControllerNamespace }); //look in this namespace to create the controller
route.DataTokens.Add("umbraco", "surface"); //ensure the umbraco token is set
route.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, "surface"); //ensure the umbraco token is set
route.DataTokens.Add("UseNamespaceFallback", false); //Don't look anywhere else except this namespace!
//make it use our custom/special SurfaceMvcHandler
route.RouteHandler = new SurfaceRouteHandler();