diff --git a/build/Build.bat b/build/Build.bat index bd18f719ad..1167d9fcb6 100644 --- a/build/Build.bat +++ b/build/Build.bat @@ -21,14 +21,6 @@ ECHO Building Umbraco %version% ReplaceIISExpressPortNumber.exe ..\src\Umbraco.Web.UI\Umbraco.Web.UI.csproj %release% -ECHO Installing the Microsoft.Bcl.Build package before anything else, otherwise you'd have to run build.cmd twice -SET nuGetFolder=%CD%\..\src\packages\ -..\src\.nuget\NuGet.exe sources Remove -Name MyGetUmbracoCore >NUL -..\src\.nuget\NuGet.exe sources Add -Name MyGetUmbracoCore -Source https://www.myget.org/F/umbracocore/api/v2/ >NUL -..\src\.nuget\NuGet.exe install ..\src\Umbraco.Web.UI\packages.config -OutputDirectory %nuGetFolder% -Verbosity quiet -..\src\.nuget\NuGet.exe install ..\src\umbraco.businesslogic\packages.config -OutputDirectory %nuGetFolder% -Verbosity quiet -..\src\.nuget\NuGet.exe install ..\src\Umbraco.Core\packages.config -OutputDirectory %nuGetFolder% -Verbosity quiet - ECHO Removing the belle build folder and bower_components folder to make sure everything is clean as a whistle RD ..\src\Umbraco.Web.UI.Client\build /Q /S RD ..\src\Umbraco.Web.UI.Client\bower_components /Q /S diff --git a/build/NuSpecs/UmbracoCms.Core.nuspec b/build/NuSpecs/UmbracoCms.Core.nuspec index f67b85be28..993b3eea7a 100644 --- a/build/NuSpecs/UmbracoCms.Core.nuspec +++ b/build/NuSpecs/UmbracoCms.Core.nuspec @@ -17,7 +17,6 @@ - @@ -37,6 +36,7 @@ + @@ -72,6 +72,7 @@ + diff --git a/build/NuSpecs/UmbracoCms.nuspec b/build/NuSpecs/UmbracoCms.nuspec index 4127ea702e..4925f90966 100644 --- a/build/NuSpecs/UmbracoCms.nuspec +++ b/build/NuSpecs/UmbracoCms.nuspec @@ -17,7 +17,7 @@ - + @@ -33,9 +33,11 @@ + + diff --git a/build/NuSpecs/tools/Dashboard.config.install.xdt b/build/NuSpecs/tools/Dashboard.config.install.xdt index 197f9c1b6f..a77632926c 100644 --- a/build/NuSpecs/tools/Dashboard.config.install.xdt +++ b/build/NuSpecs/tools/Dashboard.config.install.xdt @@ -77,4 +77,8 @@
+ +
+ +
\ No newline at end of file diff --git a/build/NuSpecs/tools/Readme.txt b/build/NuSpecs/tools/Readme.txt index 53d9c3c7da..b6b55c1c4f 100644 --- a/build/NuSpecs/tools/Readme.txt +++ b/build/NuSpecs/tools/Readme.txt @@ -10,6 +10,7 @@ Don't forget to build! + When upgrading your website using NuGet you should answer "No" to the questions to overwrite the Web.config file (and config files in the config folder). diff --git a/build/NuSpecs/tools/ReadmeUpgrade.txt b/build/NuSpecs/tools/ReadmeUpgrade.txt index 894f5e5f93..e0d660a795 100644 --- a/build/NuSpecs/tools/ReadmeUpgrade.txt +++ b/build/NuSpecs/tools/ReadmeUpgrade.txt @@ -10,6 +10,7 @@ Don't forget to build! + We've done our best to transform your configuration files but in case something is not quite right: remember we backed up your files in App_Data\NuGetBackup so you can find the original files before they were transformed. diff --git a/build/NuSpecs/tools/Web.config.install.xdt b/build/NuSpecs/tools/Web.config.install.xdt index 1cf886b312..d7fbbb2116 100644 --- a/build/NuSpecs/tools/Web.config.install.xdt +++ b/build/NuSpecs/tools/Web.config.install.xdt @@ -191,7 +191,7 @@ - + diff --git a/build/NuSpecs/tools/Web.config.uninstall.xdt b/build/NuSpecs/tools/Web.config.uninstall.xdt new file mode 100644 index 0000000000..20ba9124b7 --- /dev/null +++ b/build/NuSpecs/tools/Web.config.uninstall.xdt @@ -0,0 +1,90 @@ + + + + +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /> + /> + + \ No newline at end of file diff --git a/build/NuSpecs/tools/install.core.ps1 b/build/NuSpecs/tools/install.core.ps1 index ba6416028b..c4f213ba01 100644 --- a/build/NuSpecs/tools/install.core.ps1 +++ b/build/NuSpecs/tools/install.core.ps1 @@ -1,18 +1,30 @@ -param($rootPath, $toolsPath, $package, $project) +param($installPath, $toolsPath, $package, $project) + +Write-Host "installPath:" "${installPath}" +Write-Host "toolsPath:" "${toolsPath}" + +Write-Host " " if ($project) { $dateTime = Get-Date -Format yyyyMMdd-HHmmss - $backupPath = Join-Path (Split-Path $project.FullName -Parent) "\App_Data\NuGetBackup\$dateTime" + + # Create paths and list them + $projectPath = (Get-Item $project.Properties.Item("FullPath").Value).FullName + Write-Host "projectPath:" "${projectPath}" + $backupPath = Join-Path $projectPath "App_Data\NuGetBackup\$dateTime" + Write-Host "backupPath:" "${backupPath}" $copyLogsPath = Join-Path $backupPath "CopyLogs" - $projectDestinationPath = Split-Path $project.FullName -Parent - + Write-Host "copyLogsPath:" "${copyLogsPath}" + $umbracoBinFolder = Join-Path $projectPath "bin" + Write-Host "umbracoBinFolder:" "${umbracoBinFolder}" + # Create backup folder and logs folder if it doesn't exist yet New-Item -ItemType Directory -Force -Path $backupPath New-Item -ItemType Directory -Force -Path $copyLogsPath # After backing up, remove all umbraco dlls from bin folder in case dll files are included in the VS project # See: http://issues.umbraco.org/issue/U4-4930 - $umbracoBinFolder = Join-Path $projectDestinationPath "bin" + if(Test-Path $umbracoBinFolder) { $umbracoBinBackupPath = Join-Path $backupPath "bin" @@ -20,7 +32,7 @@ if ($project) { robocopy $umbracoBinFolder $umbracoBinBackupPath /e /LOG:$copyLogsPath\UmbracoBinBackup.log - # Delete files Umbraco brings in + # Delete files Umbraco ships with if(Test-Path $umbracoBinFolder\businesslogic.dll) { Remove-Item $umbracoBinFolder\businesslogic.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\cms.dll) { Remove-Item $umbracoBinFolder\cms.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\controls.dll) { Remove-Item $umbracoBinFolder\controls.dll -Force -Confirm:$false } @@ -36,16 +48,18 @@ if ($project) { if(Test-Path $umbracoBinFolder\umbraco.DataLayer.dll) { Remove-Item $umbracoBinFolder\umbraco.DataLayer.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\umbraco.editorControls.dll) { Remove-Item $umbracoBinFolder\umbraco.editorControls.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\umbraco.MacroEngines.dll) { Remove-Item $umbracoBinFolder\umbraco.MacroEngines.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\Umbraco.ModelsBuilder.dll) { Remove-Item $umbracoBinFolder\Umbraco.ModelsBuilder.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\Umbraco.ModelsBuilder.AspNet.dll) { Remove-Item $umbracoBinFolder\Umbraco.ModelsBuilder.AspNet.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\umbraco.providers.dll) { Remove-Item $umbracoBinFolder\umbraco.providers.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Umbraco.Web.UI.dll) { Remove-Item $umbracoBinFolder\Umbraco.Web.UI.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\UmbracoExamine.dll) { Remove-Item $umbracoBinFolder\UmbracoExamine.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\UrlRewritingNet.UrlRewriter.dll) { Remove-Item $umbracoBinFolder\UrlRewritingNet.UrlRewriter.dll -Force -Confirm:$false } # Delete files Umbraco depends upon - $amd64Folder = Join-Path $projectDestinationPath "bin\amd64" + $amd64Folder = Join-Path $umbracoBinFolder "amd64" if(Test-Path $amd64Folder) { Remove-Item $amd64Folder -Force -Recurse -Confirm:$false } - $x86Folder = Join-Path $projectDestinationPath "bin\x86" - if(Test-Path $x86Folder) { Remove-Item $x86Folder -Force -Recurse -Confirm:$false } + $x86Folder = Join-Path $umbracoBinFolder "x86" + if(Test-Path $x86Folder) { Remove-Item $x86Folder -Force -Recurse -Confirm:$false } if(Test-Path $umbracoBinFolder\AutoMapper.dll) { Remove-Item $umbracoBinFolder\AutoMapper.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\AutoMapper.Net4.dll) { Remove-Item $umbracoBinFolder\AutoMapper.Net4.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\ClientDependency.Core.dll) { Remove-Item $umbracoBinFolder\ClientDependency.Core.dll -Force -Confirm:$false } @@ -59,6 +73,8 @@ if ($project) { if(Test-Path $umbracoBinFolder\Lucene.Net.dll) { Remove-Item $umbracoBinFolder\Lucene.Net.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Microsoft.AspNet.Identity.Core.dll) { Remove-Item $umbracoBinFolder\Microsoft.AspNet.Identity.Core.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Microsoft.AspNet.Identity.Owin.dll) { Remove-Item $umbracoBinFolder\Microsoft.AspNet.Identity.Owin.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\Microsoft.CodeAnalysis.CSharp.dll) { Remove-Item $umbracoBinFolder\Microsoft.CodeAnalysis.CSharp.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\Microsoft.CodeAnalysis.dll) { Remove-Item $umbracoBinFolder\Microsoft.CodeAnalysis.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Microsoft.Owin.dll) { Remove-Item $umbracoBinFolder\Microsoft.Owin.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Microsoft.Owin.Host.SystemWeb.dll) { Remove-Item $umbracoBinFolder\Microsoft.Owin.Host.SystemWeb.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Microsoft.Owin.Security.dll) { Remove-Item $umbracoBinFolder\Microsoft.Owin.Security.dll -Force -Confirm:$false } @@ -72,6 +88,8 @@ if ($project) { if(Test-Path $umbracoBinFolder\Newtonsoft.Json.dll) { Remove-Item $umbracoBinFolder\Newtonsoft.Json.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Owin.dll) { Remove-Item $umbracoBinFolder\Owin.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\Semver.dll) { Remove-Item $umbracoBinFolder\Semver.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\System.Collections.Immutable.dll) { Remove-Item $umbracoBinFolder\System.Collections.Immutable.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\System.Reflection.Metadata.dll) { Remove-Item $umbracoBinFolder\System.Reflection.Metadata.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\System.Net.Http.Extensions.dll) { Remove-Item $umbracoBinFolder\System.Net.Http.Extensions.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\System.Net.Http.Formatting.dll) { Remove-Item $umbracoBinFolder\System.Net.Http.Formatting.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\System.Net.Http.Primitives.dll) { Remove-Item $umbracoBinFolder\System.Net.Http.Primitives.dll -Force -Confirm:$false } @@ -82,6 +100,6 @@ if ($project) { if(Test-Path $umbracoBinFolder\System.Web.Razor.dll) { Remove-Item $umbracoBinFolder\System.Web.Razor.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\System.Web.WebPages.dll) { Remove-Item $umbracoBinFolder\System.Web.WebPages.dll -Force -Confirm:$false } if(Test-Path $umbracoBinFolder\System.Web.WebPages.Deployment.dll) { Remove-Item $umbracoBinFolder\System.Web.WebPages.Deployment.dll -Force -Confirm:$false } - if(Test-Path $umbracoBinFolder\System.Web.WebPages.Razor.dll) { Remove-Item $umbracoBinFolder\System.Web.WebPages.Razor.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\System.Web.WebPages.Razor.dll) { Remove-Item $umbracoBinFolder\System.Web.WebPages.Razor.dll -Force -Confirm:$false } } } \ No newline at end of file diff --git a/build/NuSpecs/tools/install.ps1 b/build/NuSpecs/tools/install.ps1 index 49b49f6cfe..de7a6cc16e 100644 --- a/build/NuSpecs/tools/install.ps1 +++ b/build/NuSpecs/tools/install.ps1 @@ -1,21 +1,33 @@ -param($rootPath, $toolsPath, $package, $project) +param($installPath, $toolsPath, $package, $project) + +Write-Host "installPath:" "${installPath}" +Write-Host "toolsPath:" "${toolsPath}" + +Write-Host " " if ($project) { $dateTime = Get-Date -Format yyyyMMdd-HHmmss - $backupPath = Join-Path (Split-Path $project.FullName -Parent) "\App_Data\NuGetBackup\$dateTime" + + # Create paths and list them + $projectPath = (Get-Item $project.Properties.Item("FullPath").Value).FullName + Write-Host "projectPath:" "${projectPath}" + $backupPath = Join-Path $projectPath "App_Data\NuGetBackup\$dateTime" + Write-Host "backupPath:" "${backupPath}" $copyLogsPath = Join-Path $backupPath "CopyLogs" - $projectDestinationPath = Split-Path $project.FullName -Parent + Write-Host "copyLogsPath:" "${copyLogsPath}" + $webConfigSource = Join-Path $projectPath "Web.config" + Write-Host "webConfigSource:" "${webConfigSource}" + $configFolder = Join-Path $projectPath "Config" + Write-Host "configFolder:" "${configFolder}" # Create backup folder and logs folder if it doesn't exist yet New-Item -ItemType Directory -Force -Path $backupPath New-Item -ItemType Directory -Force -Path $copyLogsPath # Create a backup of original web.config - $webConfigSource = Join-Path $projectDestinationPath "Web.config" Copy-Item $webConfigSource $backupPath -Force - # Backup config files folder - $configFolder = Join-Path $projectDestinationPath "Config" + # Backup config files folder if(Test-Path $configFolder) { $umbracoBackupPath = Join-Path $backupPath "Config" New-Item -ItemType Directory -Force -Path $umbracoBackupPath @@ -24,32 +36,24 @@ if ($project) { } # Copy umbraco and umbraco_files from package to project folder - # This is only done when these folders already exist because we - # only want to do this for upgrades - $umbracoFolder = Join-Path $projectDestinationPath "Umbraco" - if(Test-Path $umbracoFolder) { - $umbracoFolderSource = Join-Path $rootPath "UmbracoFiles\Umbraco" - - $umbracoBackupPath = Join-Path $backupPath "Umbraco" - New-Item -ItemType Directory -Force -Path $umbracoBackupPath - - robocopy $umbracoFolder $umbracoBackupPath /e /LOG:$copyLogsPath\UmbracoBackup.log - robocopy $umbracoFolderSource $umbracoFolder /is /it /e /xf UI.xml /LOG:$copyLogsPath\UmbracoCopy.log - } + $umbracoFolder = Join-Path $projectPath "Umbraco" + New-Item -ItemType Directory -Force -Path $umbracoFolder + $umbracoFolderSource = Join-Path $installPath "UmbracoFiles\Umbraco" + $umbracoBackupPath = Join-Path $backupPath "Umbraco" + New-Item -ItemType Directory -Force -Path $umbracoBackupPath + robocopy $umbracoFolder $umbracoBackupPath /e /LOG:$copyLogsPath\UmbracoBackup.log + robocopy $umbracoFolderSource $umbracoFolder /is /it /e /xf UI.xml /LOG:$copyLogsPath\UmbracoCopy.log - $umbracoClientFolder = Join-Path $projectDestinationPath "Umbraco_Client" - if(Test-Path $umbracoClientFolder) { - $umbracoClientFolderSource = Join-Path $rootPath "UmbracoFiles\Umbraco_Client" - - $umbracoClientBackupPath = Join-Path $backupPath "Umbraco_Client" - New-Item -ItemType Directory -Force -Path $umbracoClientBackupPath - - robocopy $umbracoClientFolder $umbracoClientBackupPath /e /LOG:$copyLogsPath\UmbracoClientBackup.log - robocopy $umbracoClientFolderSource $umbracoClientFolder /is /it /e /LOG:$copyLogsPath\UmbracoClientCopy.log - } + $umbracoClientFolder = Join-Path $projectPath "Umbraco_Client" + New-Item -ItemType Directory -Force -Path $umbracoClientFolder + $umbracoClientFolderSource = Join-Path $installPath "UmbracoFiles\Umbraco_Client" + $umbracoClientBackupPath = Join-Path $backupPath "Umbraco_Client" + New-Item -ItemType Directory -Force -Path $umbracoClientBackupPath + robocopy $umbracoClientFolder $umbracoClientBackupPath /e /LOG:$copyLogsPath\UmbracoClientBackup.log + robocopy $umbracoClientFolderSource $umbracoClientFolder /is /it /e /LOG:$copyLogsPath\UmbracoClientCopy.log $copyWebconfig = $true - $destinationWebConfig = Join-Path $projectDestinationPath "Web.config" + $destinationWebConfig = Join-Path $projectPath "Web.config" if(Test-Path $destinationWebConfig) { @@ -71,11 +75,11 @@ if ($project) { if($copyWebconfig -eq $true) { - $packageWebConfigSource = Join-Path $rootPath "UmbracoFiles\Web.config" + $packageWebConfigSource = Join-Path $installPath "UmbracoFiles\Web.config" Copy-Item $packageWebConfigSource $destinationWebConfig -Force } - $installFolder = Join-Path $projectDestinationPath "Install" + $installFolder = Join-Path $projectPath "Install" if(Test-Path $installFolder) { Remove-Item $installFolder -Force -Recurse -Confirm:$false } diff --git a/build/NuSpecs/tools/uninstall.core.ps1 b/build/NuSpecs/tools/uninstall.core.ps1 new file mode 100644 index 0000000000..3daa6a1ba7 --- /dev/null +++ b/build/NuSpecs/tools/uninstall.core.ps1 @@ -0,0 +1,48 @@ +param($installPath, $toolsPath, $package, $project) + +Write-Host "installPath:" "${installPath}" +Write-Host "toolsPath:" "${toolsPath}" + +Write-Host " " + +if ($project) { + + # Create paths and list them + $projectPath = (Get-Item $project.Properties.Item("FullPath").Value).FullName + Write-Host "projectPath:" "${projectPath}" + $backupPath = Join-Path $projectPath "App_Data\NuGetBackup" + Write-Host "backupPath:" "${backupPath}" + $umbracoBinFolder = Join-Path $projectPath "bin" + Write-Host "umbracoBinFolder:" "${umbracoBinFolder}" + + # Remove backups + Write-Host "removing backups:" "${backupPath}" + if(Test-Path $backupPath) { Remove-Item -Recurse -Force $backupPath -Confirm:$false } + + # Delete files Umbraco ships with + + Write-Host "removing dlls:" "${umbracoBinFolder}" + if(Test-Path $umbracoBinFolder\businesslogic.dll) { Remove-Item $umbracoBinFolder\businesslogic.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\cms.dll) { Remove-Item $umbracoBinFolder\cms.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\controls.dll) { Remove-Item $umbracoBinFolder\controls.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\interfaces.dll) { Remove-Item $umbracoBinFolder\interfaces.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\log4net.dll) { Remove-Item $umbracoBinFolder\log4net.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\Microsoft.ApplicationBlocks.Data.dll) { Remove-Item $umbracoBinFolder\Microsoft.ApplicationBlocks.Data.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\SQLCE4Umbraco.dll) { Remove-Item $umbracoBinFolder\SQLCE4Umbraco.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\System.Data.SqlServerCe.dll) { Remove-Item $umbracoBinFolder\System.Data.SqlServerCe.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\System.Data.SqlServerCe.Entity.dll) { Remove-Item $umbracoBinFolder\System.Data.SqlServerCe.Entity.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\TidyNet.dll) { Remove-Item $umbracoBinFolder\TidyNet.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\umbraco.dll) { Remove-Item $umbracoBinFolder\umbraco.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\Umbraco.Core.dll) { Remove-Item $umbracoBinFolder\Umbraco.Core.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\umbraco.DataLayer.dll) { Remove-Item $umbracoBinFolder\umbraco.DataLayer.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\umbraco.editorControls.dll) { Remove-Item $umbracoBinFolder\umbraco.editorControls.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\umbraco.MacroEngines.dll) { Remove-Item $umbracoBinFolder\umbraco.MacroEngines.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\umbraco.providers.dll) { Remove-Item $umbracoBinFolder\umbraco.providers.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\Umbraco.Web.UI.dll) { Remove-Item $umbracoBinFolder\Umbraco.Web.UI.dll -Force -Confirm:$false } + if(Test-Path $umbracoBinFolder\UmbracoExamine.dll) { Remove-Item $umbracoBinFolder\UmbracoExamine.dll -Force -Confirm:$false } + + $amd64Folder = Join-Path $umbracoBinFolder "amd64" + if(Test-Path $amd64Folder) { Remove-Item $amd64Folder -Force -Recurse -Confirm:$false } + $x86Folder = Join-Path $umbracoBinFolder "x86" + if(Test-Path $x86Folder) { Remove-Item $x86Folder -Force -Recurse -Confirm:$false } +} \ No newline at end of file diff --git a/build/NuSpecs/tools/uninstall.ps1 b/build/NuSpecs/tools/uninstall.ps1 new file mode 100644 index 0000000000..4f7dd35384 --- /dev/null +++ b/build/NuSpecs/tools/uninstall.ps1 @@ -0,0 +1,39 @@ +param($installPath, $toolsPath, $package, $project) + +Write-Host "installPath:" "${installPath}" +Write-Host "toolsPath:" "${toolsPath}" + +Write-Host " " + +if ($project) { + + # Create paths and list them + $projectPath = (Get-Item $project.Properties.Item("FullPath").Value).FullName + Write-Host "projectPath:" "${projectPath}" + $backupPath = Join-Path $projectPath "App_Data\NuGetBackup" + Write-Host "backupPath:" "${backupPath}" + $appBrowsers = Join-Path $projectPath "App_Browsers" + Write-Host "appBrowsers:" "${appBrowsers}" + $appData = Join-Path $projectPath "App_Data" + Write-Host "appData:" "${appData}" + + # Remove backups + Write-Host "removing backups:" "${backupPath}" + if(Test-Path $backupPath) { Remove-Item -Recurse -Force $backupPath -Confirm:$false } + + # Remove app_data files + Write-Host "removing app_data files:" "${appData}" + if(Test-Path $appData\packages) { Remove-Item $appData\packages -Recurse -Force -Confirm:$false } + + Write-Host "removing app_browsers:" "${appBrowsers}" + if(Test-Path $appBrowsers\Form.browser) { Remove-Item $appBrowsers\Form.browser -Force -Confirm:$false } + if(Test-Path $appBrowsers\w3cvalidator.browser) { Remove-Item $appBrowsers\w3cvalidator.browser -Force -Confirm:$false } + + # Remove umbraco and umbraco_files + $umbracoFolder = Join-Path $projectPath "Umbraco" + Write-Host "removing umbraco folder:" "${umbracoFolder}" + if(Test-Path $umbracoFolder) { Remove-Item $umbracoFolder -Recurse -Force -Confirm:$false } + $umbracoClientFolder = Join-Path $projectPath "Umbraco_Client" + Write-Host "removing umbraco client folder:" "${umbracoClientFolder}" + if(Test-Path $umbracoClientFolder) { Remove-Item $umbracoClientFolder -Recurse -Force -Confirm:$false } +} diff --git a/build/UmbracoVersion.txt b/build/UmbracoVersion.txt index 2a8a3618d4..8cc23a423e 100644 --- a/build/UmbracoVersion.txt +++ b/build/UmbracoVersion.txt @@ -1,3 +1,3 @@ # Usage: on line 2 put the release version, on line 3 put the version comment (example: beta) 7.4.0 -beta4 \ No newline at end of file +RC1 \ No newline at end of file diff --git a/src/SolutionInfo.cs b/src/SolutionInfo.cs index f385151454..f51970c7c9 100644 --- a/src/SolutionInfo.cs +++ b/src/SolutionInfo.cs @@ -12,4 +12,4 @@ using System.Resources; [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("7.4.0")] -[assembly: AssemblyInformationalVersion("7.4.0-beta4")] \ No newline at end of file +[assembly: AssemblyInformationalVersion("7.4.0-RC1")] \ No newline at end of file diff --git a/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs index 861c6b803e..0ae721943d 100644 --- a/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs +++ b/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs @@ -7,14 +7,22 @@ using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Cache { + /// + /// Interface describing this cache provider as a wrapper for another + /// + internal interface IRuntimeCacheProviderWrapper + { + IRuntimeCacheProvider InnerProvider { get; } + } + /// /// 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 /// - 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) { diff --git a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs index 45e79a1b67..1f51fc3ccc 100644 --- a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs @@ -15,35 +15,31 @@ namespace Umbraco.Core.Cache /// This cache policy uses sliding expiration and caches instances for 5 minutes. However if allow zero count is true, then we use the /// default policy with no expiry. /// - internal class DefaultRepositoryCachePolicy : DisposableObject, IRepositoryCachePolicy + internal class DefaultRepositoryCachePolicy : RepositoryCachePolicyBase where TEntity : class, IAggregateRoot { private readonly RepositoryCachePolicyOptions _options; - protected IRuntimeCacheProvider Cache { get; private set; } - private Action _action; public DefaultRepositoryCachePolicy(IRuntimeCacheProvider cache, RepositoryCachePolicyOptions options) - { - if (cache == null) throw new ArgumentNullException("cache"); + : base(cache) + { if (options == null) throw new ArgumentNullException("options"); - - _options = options; - Cache = cache; + _options = options; } - public string GetCacheIdKey(object id) + protected string GetCacheIdKey(object id) { if (id == null) throw new ArgumentNullException("id"); return string.Format("{0}{1}", GetCacheTypeKey(), id); } - public string GetCacheTypeKey() + protected string GetCacheTypeKey() { return string.Format("uRepo_{0}_", typeof(TEntity).Name); } - public void CreateOrUpdate(TEntity entity, Action persistMethod) + public override void CreateOrUpdate(TEntity entity, Action persistMethod) { if (entity == null) throw new ArgumentNullException("entity"); if (persistMethod == null) throw new ArgumentNullException("persistMethod"); @@ -85,24 +81,29 @@ namespace Umbraco.Core.Cache } } - public void Remove(TEntity entity, Action persistMethod) + public override void Remove(TEntity entity, Action persistMethod) { if (entity == null) throw new ArgumentNullException("entity"); if (persistMethod == null) throw new ArgumentNullException("persistMethod"); - persistMethod(entity); - - //set the disposal action - var cacheKey = GetCacheIdKey(entity.Id); - SetCacheAction(() => + try { - Cache.ClearCacheItem(cacheKey); - //If there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetCacheTypeKey()); - }); + persistMethod(entity); + } + finally + { + //set the disposal action + var cacheKey = GetCacheIdKey(entity.Id); + SetCacheAction(() => + { + Cache.ClearCacheItem(cacheKey); + //If there's a GetAllCacheAllowZeroCount cache, ensure it is cleared + Cache.ClearCacheItem(GetCacheTypeKey()); + }); + } } - public TEntity Get(TId id, Func getFromRepo) + public override TEntity Get(TId id, Func getFromRepo) { if (getFromRepo == null) throw new ArgumentNullException("getFromRepo"); @@ -119,13 +120,13 @@ namespace Umbraco.Core.Cache return entity; } - public TEntity Get(TId id) + public override TEntity Get(TId id) { var cacheKey = GetCacheIdKey(id); return Cache.GetCacheItem(cacheKey); } - public bool Exists(TId id, Func getFromRepo) + public override bool Exists(TId id, Func getFromRepo) { if (getFromRepo == null) throw new ArgumentNullException("getFromRepo"); @@ -134,7 +135,7 @@ namespace Umbraco.Core.Cache return fromCache != null || getFromRepo(id); } - public virtual TEntity[] GetAll(TId[] ids, Func> getFromRepo) + public override TEntity[] GetAll(TId[] ids, Func> getFromRepo) { if (getFromRepo == null) throw new ArgumentNullException("getFromRepo"); @@ -188,7 +189,7 @@ namespace Umbraco.Core.Cache /// Looks up the zero count cache, must return null if it doesn't exist /// /// - protected virtual bool HasZeroCountCache() + protected bool HasZeroCountCache() { var zeroCount = Cache.GetCacheItem(GetCacheTypeKey()); return (zeroCount != null && zeroCount.Any() == false); @@ -198,24 +199,13 @@ namespace Umbraco.Core.Cache /// Performs the lookup for all entities of this type from the cache /// /// - protected virtual TEntity[] GetAllFromCache() + protected TEntity[] GetAllFromCache() { var allEntities = Cache.GetCacheItemsByKeySearch(GetCacheTypeKey()) .WhereNotNull() .ToArray(); return allEntities.Any() ? allEntities : new TEntity[] {}; - } - - /// - /// The disposal performs the caching - /// - protected override void DisposeResources() - { - if (_action != null) - { - _action(); - } - } + } /// /// Sets the action to execute on disposal for a single entity @@ -273,14 +263,6 @@ namespace Umbraco.Core.Cache } }); } - - /// - /// Sets the action to execute on disposal - /// - /// - protected void SetCacheAction(Action action) - { - _action = action; - } + } } \ No newline at end of file diff --git a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs index c098af8992..9b37d1861f 100644 --- a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs @@ -11,40 +11,157 @@ namespace Umbraco.Core.Cache /// /// /// - /// - /// This caching policy has no sliding expiration but uses the default ObjectCache.InfiniteAbsoluteExpiration as it's timeout, so it - /// should not leave the cache unless the cache memory is exceeded and it gets thrown out. - /// - internal class FullDataSetRepositoryCachePolicy : DefaultRepositoryCachePolicy + internal class FullDataSetRepositoryCachePolicy : RepositoryCachePolicyBase where TEntity : class, IAggregateRoot { private readonly Func _getEntityId; + private readonly Func> _getAllFromRepo; + private readonly bool _expires; - public FullDataSetRepositoryCachePolicy(IRuntimeCacheProvider cache, Func getEntityId) : base(cache, - new RepositoryCachePolicyOptions - { - //Definitely allow zero'd cache entires since this is a full set, in many cases there will be none, - // and we must cache this! - GetAllCacheAllowZeroCount = true - }) + public FullDataSetRepositoryCachePolicy(IRuntimeCacheProvider cache, Func getEntityId, Func> getAllFromRepo, bool expires) + : base(cache) { _getEntityId = getEntityId; + _getAllFromRepo = getAllFromRepo; + _expires = expires; } private bool? _hasZeroCountCache; + protected string GetCacheTypeKey() + { + return string.Format("uRepo_{0}_", typeof(TEntity).Name); + } + + public override void CreateOrUpdate(TEntity entity, Action persistMethod) + { + if (entity == null) throw new ArgumentNullException("entity"); + if (persistMethod == null) throw new ArgumentNullException("persistMethod"); + + try + { + persistMethod(entity); + + //set the disposal action + SetCacheAction(() => + { + //Clear all + Cache.ClearCacheItem(GetCacheTypeKey()); + }); + } + catch + { + //set the disposal action + SetCacheAction(() => + { + //Clear all + Cache.ClearCacheItem(GetCacheTypeKey()); + }); + throw; + } + } + + public override void Remove(TEntity entity, Action persistMethod) + { + if (entity == null) throw new ArgumentNullException("entity"); + if (persistMethod == null) throw new ArgumentNullException("persistMethod"); + + try + { + persistMethod(entity); + } + finally + { + //set the disposal action + SetCacheAction(() => + { + //Clear all + Cache.ClearCacheItem(GetCacheTypeKey()); + }); + } + } + + public override TEntity Get(TId id, Func getFromRepo) + { + //Force get all with cache + var found = GetAll(new TId[] { }, ids => _getAllFromRepo().WhereNotNull()); + + //we don't have anything in cache (this should never happen), just return from the repo + if (found == null) return getFromRepo(id); + var entity = found.FirstOrDefault(x => _getEntityId(x).Equals(id)); + if (entity == null) return null; + + //We must ensure to deep clone each one out manually since the deep clone list only clones one way + return (TEntity)entity.DeepClone(); + } + + public override TEntity Get(TId id) + { + //Force get all with cache + var found = GetAll(new TId[] { }, ids => _getAllFromRepo().WhereNotNull()); + + //we don't have anything in cache (this should never happen), just return null + if (found == null) return null; + var entity = found.FirstOrDefault(x => _getEntityId(x).Equals(id)); + if (entity == null) return null; + + //We must ensure to deep clone each one out manually since the deep clone list only clones one way + return (TEntity)entity.DeepClone(); + } + + public override bool Exists(TId id, Func getFromRepo) + { + //Force get all with cache + var found = GetAll(new TId[] { }, ids => _getAllFromRepo().WhereNotNull()); + + //we don't have anything in cache (this should never happen), just return from the repo + return found == null + ? getFromRepo(id) + : found.Any(x => _getEntityId(x).Equals(id)); + } + public override TEntity[] GetAll(TId[] ids, Func> getFromRepo) { - //process the base logic without any Ids - we want to cache them all! - var result = base.GetAll(new TId[] { }, getFromRepo); + //process getting all including setting the cache callback + var result = PerformGetAll(getFromRepo); //now that the base result has been calculated, they will all be cached. // Now we can just filter by ids if they have been supplied - - return ids.Any() - ? result.Where(x => ids.Contains(_getEntityId(x))).ToArray() - : result; + + return (ids.Any() + ? result.Where(x => ids.Contains(_getEntityId(x))).ToArray() + : result) + //We must ensure to deep clone each one out manually since the deep clone list only clones one way + .Select(x => (TEntity)x.DeepClone()) + .ToArray(); + } + + private TEntity[] PerformGetAll(Func> getFromRepo) + { + var allEntities = GetAllFromCache(); + if (allEntities.Any()) + { + return allEntities; + } + + //check the zero count cache + if (HasZeroCountCache()) + { + //there is a zero count cache so return an empty list + return new TEntity[] { }; + } + + //we need to do the lookup from the repo + var entityCollection = getFromRepo(new TId[] { }) + //ensure we don't include any null refs in the returned collection! + .WhereNotNull() + .ToArray(); + + //set the disposal action + SetCacheAction(entityCollection); + + return entityCollection; } /// @@ -52,26 +169,32 @@ namespace Umbraco.Core.Cache /// /// /// - protected override void SetCacheAction(string cacheKey, TEntity entity) + protected void SetCacheAction(string cacheKey, TEntity entity) { - //do nothing + //No-op } /// /// Sets the action to execute on disposal for an entity collection /// - /// /// - protected override void SetCacheAction(TId[] ids, TEntity[] entityCollection) + protected void SetCacheAction(TEntity[] entityCollection) { - //for this type of caching policy, we don't want to cache any GetAll request containing specific Ids - if (ids.Any()) return; - //set the disposal action SetCacheAction(() => { //We want to cache the result as a single collection - Cache.InsertCacheItem(GetCacheTypeKey(), () => new DeepCloneableList(entityCollection)); + + if (_expires) + { + Cache.InsertCacheItem(GetCacheTypeKey(), () => new DeepCloneableList(entityCollection), + timeout: TimeSpan.FromMinutes(5), + isSliding: true); + } + else + { + Cache.InsertCacheItem(GetCacheTypeKey(), () => new DeepCloneableList(entityCollection)); + } }); } @@ -79,7 +202,7 @@ namespace Umbraco.Core.Cache /// Looks up the zero count cache, must return null if it doesn't exist /// /// - protected override bool HasZeroCountCache() + protected bool HasZeroCountCache() { if (_hasZeroCountCache.HasValue) return _hasZeroCountCache.Value; @@ -92,14 +215,15 @@ namespace Umbraco.Core.Cache /// This policy will cache the full data set as a single collection /// /// - protected override TEntity[] GetAllFromCache() + protected TEntity[] GetAllFromCache() { var found = Cache.GetCacheItem>(GetCacheTypeKey()); - + //This method will get called before checking for zero count cache, so we'll just set the flag here _hasZeroCountCache = found != null; return found == null ? new TEntity[] { } : found.WhereNotNull().ToArray(); } + } } \ No newline at end of file diff --git a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicyFactory.cs b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicyFactory.cs index 6a79c2b8c2..e4addcf355 100644 --- a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicyFactory.cs +++ b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicyFactory.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Cache @@ -13,16 +14,20 @@ namespace Umbraco.Core.Cache { private readonly IRuntimeCacheProvider _runtimeCache; private readonly Func _getEntityId; + private readonly Func> _getAllFromRepo; + private readonly bool _expires; - public FullDataSetRepositoryCachePolicyFactory(IRuntimeCacheProvider runtimeCache, Func getEntityId) + public FullDataSetRepositoryCachePolicyFactory(IRuntimeCacheProvider runtimeCache, Func getEntityId, Func> getAllFromRepo, bool expires) { _runtimeCache = runtimeCache; _getEntityId = getEntityId; + _getAllFromRepo = getAllFromRepo; + _expires = expires; } public virtual IRepositoryCachePolicy CreatePolicy() { - return new FullDataSetRepositoryCachePolicy(_runtimeCache, _getEntityId); + return new FullDataSetRepositoryCachePolicy(_runtimeCache, _getEntityId, _getAllFromRepo, _expires); } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Cache/IRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/IRepositoryCachePolicy.cs index 97844933b7..215487c3be 100644 --- a/src/Umbraco.Core/Cache/IRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/IRepositoryCachePolicy.cs @@ -10,9 +10,7 @@ namespace Umbraco.Core.Cache TEntity Get(TId id, Func getFromRepo); TEntity Get(TId id); bool Exists(TId id, Func getFromRepo); - - string GetCacheIdKey(object id); - string GetCacheTypeKey(); + void CreateOrUpdate(TEntity entity, Action persistMethod); void Remove(TEntity entity, Action persistMethod); TEntity[] GetAll(TId[] ids, Func> getFromRepo); diff --git a/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs new file mode 100644 index 0000000000..b939cd14e6 --- /dev/null +++ b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using Umbraco.Core.Models.EntityBase; + +namespace Umbraco.Core.Cache +{ + internal abstract class RepositoryCachePolicyBase : DisposableObject, IRepositoryCachePolicy + where TEntity : class, IAggregateRoot + { + private Action _action; + + protected RepositoryCachePolicyBase(IRuntimeCacheProvider cache) + { + if (cache == null) throw new ArgumentNullException("cache"); + + Cache = cache; + } + + protected IRuntimeCacheProvider Cache { get; private set; } + + /// + /// The disposal performs the caching + /// + protected override void DisposeResources() + { + if (_action != null) + { + _action(); + } + } + + /// + /// Sets the action to execute on disposal + /// + /// + protected void SetCacheAction(Action action) + { + _action = action; + } + + public abstract TEntity Get(TId id, Func getFromRepo); + public abstract TEntity Get(TId id); + public abstract bool Exists(TId id, Func getFromRepo); + public abstract void CreateOrUpdate(TEntity entity, Action persistMethod); + public abstract void Remove(TEntity entity, Action persistMethod); + public abstract TEntity[] GetAll(TId[] ids, Func> getFromRepo); + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs index 9566cd6e7f..28ac4ee2d1 100644 --- a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs @@ -18,7 +18,7 @@ namespace Umbraco.Core.Cache protected override void SetCacheAction(TId[] ids, TEntity[] entityCollection) { - //do nothing + //no-op } } } \ No newline at end of file diff --git a/src/Umbraco.Core/CacheHelper.cs b/src/Umbraco.Core/CacheHelper.cs index 4b009e5f86..0dc5f5b00f 100644 --- a/src/Umbraco.Core/CacheHelper.cs +++ b/src/Umbraco.Core/CacheHelper.cs @@ -290,7 +290,7 @@ namespace Umbraco.Core TimeSpan timeout, Func 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 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 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 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; + } + } } diff --git a/src/Umbraco.Core/Collections/DeepCloneableList.cs b/src/Umbraco.Core/Collections/DeepCloneableList.cs index 365bf53b06..5067562aa7 100644 --- a/src/Umbraco.Core/Collections/DeepCloneableList.cs +++ b/src/Umbraco.Core/Collections/DeepCloneableList.cs @@ -14,18 +14,24 @@ namespace Umbraco.Core.Collections /// internal class DeepCloneableList : List, IDeepCloneable, IRememberBeingDirty { - /// - /// Initializes a new instance of the class that is empty and has the default initial capacity. - /// - public DeepCloneableList() + private readonly ListCloneBehavior _listCloneBehavior; + + public DeepCloneableList(ListCloneBehavior listCloneBehavior) { + _listCloneBehavior = listCloneBehavior; + } + + public DeepCloneableList(IEnumerable collection, ListCloneBehavior listCloneBehavior) : base(collection) + { + _listCloneBehavior = listCloneBehavior; } /// - /// Initializes a new instance of the class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied. + /// Default behavior is CloneOnce /// - /// The collection whose elements are copied to the new list. is null. - public DeepCloneableList(IEnumerable collection) : base(collection) + /// + public DeepCloneableList(IEnumerable collection) + : this(collection, ListCloneBehavior.CloneOnce) { } @@ -35,20 +41,47 @@ namespace Umbraco.Core.Collections /// public object DeepClone() { - var newList = new DeepCloneableList(); - foreach (var item in this) + switch (_listCloneBehavior) { - var dc = item as IDeepCloneable; - if (dc != null) - { - newList.Add((T) dc.DeepClone()); - } - else - { - newList.Add(item); - } + case ListCloneBehavior.CloneOnce: + //we are cloning once, so create a new list in none mode + // and deep clone all items into it + var newList = new DeepCloneableList(ListCloneBehavior.None); + foreach (var item in this) + { + var dc = item as IDeepCloneable; + if (dc != null) + { + newList.Add((T)dc.DeepClone()); + } + else + { + newList.Add(item); + } + } + return newList; + case ListCloneBehavior.None: + //we are in none mode, so just return a new list with the same items + return new DeepCloneableList(this, ListCloneBehavior.None); + case ListCloneBehavior.Always: + //always clone to new list + var newList2 = new DeepCloneableList(ListCloneBehavior.Always); + foreach (var item in this) + { + var dc = item as IDeepCloneable; + if (dc != null) + { + newList2.Add((T)dc.DeepClone()); + } + else + { + newList2.Add(item); + } + } + return newList2; + default: + throw new ArgumentOutOfRangeException(); } - return newList; } public bool IsDirty() diff --git a/src/Umbraco.Core/Collections/ListCloneBehavior.cs b/src/Umbraco.Core/Collections/ListCloneBehavior.cs new file mode 100644 index 0000000000..4fe935f7ff --- /dev/null +++ b/src/Umbraco.Core/Collections/ListCloneBehavior.cs @@ -0,0 +1,20 @@ +namespace Umbraco.Core.Collections +{ + internal enum ListCloneBehavior + { + /// + /// When set, DeepClone will clone the items one time and the result list behavior will be None + /// + CloneOnce, + + /// + /// When set, DeepClone will not clone any items + /// + None, + + /// + /// When set, DeepClone will always clone all items + /// + Always + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoVersion.cs b/src/Umbraco.Core/Configuration/UmbracoVersion.cs index 4039ab7db0..02a9a64893 100644 --- a/src/Umbraco.Core/Configuration/UmbracoVersion.cs +++ b/src/Umbraco.Core/Configuration/UmbracoVersion.cs @@ -24,7 +24,7 @@ namespace Umbraco.Core.Configuration /// Gets the version comment (like beta or RC). /// /// The version comment. - public static string CurrentComment { get { return "beta4"; } } + public static string CurrentComment { get { return "RC1"; } } // Get the version of the umbraco.dll by looking at a class in that dll // Had to do it like this due to medium trust issues, see: http://haacked.com/archive/2010/11/04/assembly-location-and-medium-trust.aspx diff --git a/src/Umbraco.Core/CoreBootManager.cs b/src/Umbraco.Core/CoreBootManager.cs index d2dea09698..4da740f458 100644 --- a/src/Umbraco.Core/CoreBootManager.cs +++ b/src/Umbraco.Core/CoreBootManager.cs @@ -136,7 +136,10 @@ namespace Umbraco.Core { try { - x.OnApplicationInitialized(UmbracoApplication, ApplicationContext); + using (ProfilingLogger.DebugDuration(string.Format("Executing {0} in ApplicationInitialized", x.GetType()))) + { + x.OnApplicationInitialized(UmbracoApplication, ApplicationContext); + } } catch (Exception ex) { @@ -299,7 +302,10 @@ namespace Umbraco.Core { try { - x.OnApplicationStarting(UmbracoApplication, ApplicationContext); + using (ProfilingLogger.DebugDuration(string.Format("Executing {0} in ApplicationStarting", x.GetType()))) + { + x.OnApplicationStarting(UmbracoApplication, ApplicationContext); + } } catch (Exception ex) { @@ -350,7 +356,10 @@ namespace Umbraco.Core { try { - x.OnApplicationStarted(UmbracoApplication, ApplicationContext); + using (ProfilingLogger.DebugDuration(string.Format("Executing {0} in ApplicationStarted", x.GetType()))) + { + x.OnApplicationStarted(UmbracoApplication, ApplicationContext); + } } catch (Exception ex) { diff --git a/src/Umbraco.Core/Models/DeepCloneHelper.cs b/src/Umbraco.Core/Models/DeepCloneHelper.cs index 7523555c24..c1b45f63ce 100644 --- a/src/Umbraco.Core/Models/DeepCloneHelper.cs +++ b/src/Umbraco.Core/Models/DeepCloneHelper.cs @@ -9,10 +9,30 @@ namespace Umbraco.Core.Models { public static class DeepCloneHelper { + /// + /// Stores the metadata for the properties for a given type so we know how to create them + /// + private struct ClonePropertyInfo + { + public ClonePropertyInfo(PropertyInfo propertyInfo) : this() + { + if (propertyInfo == null) throw new ArgumentNullException("propertyInfo"); + PropertyInfo = propertyInfo; + } + + public PropertyInfo PropertyInfo { get; private set; } + public bool IsDeepCloneable { get; set; } + public Type GenericListType { get; set; } + public bool IsList + { + get { return GenericListType != null; } + } + } + /// /// Used to avoid constant reflection (perf) /// - private static readonly ConcurrentDictionary PropCache = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary PropCache = new ConcurrentDictionary(); /// /// Used to deep clone any reference properties on the object (should be done after a MemberwiseClone for which the outcome is 'output') @@ -30,81 +50,99 @@ namespace Umbraco.Core.Models throw new InvalidOperationException("Both the input and output types must be the same"); } + //get the property metadata from cache so we only have to figure this out once per type var refProperties = PropCache.GetOrAdd(inputType, type => inputType.GetProperties() - .Where(x => - //is not attributed with the ignore clone attribute - x.GetCustomAttribute() == null + .Select(propertyInfo => + { + if ( + //is not attributed with the ignore clone attribute + propertyInfo.GetCustomAttribute() != null //reference type but not string - && x.PropertyType.IsValueType == false && x.PropertyType != typeof (string) + || propertyInfo.PropertyType.IsValueType || propertyInfo.PropertyType == typeof (string) //settable - && x.CanWrite + || propertyInfo.CanWrite == false //non-indexed - && x.GetIndexParameters().Any() == false) + || propertyInfo.GetIndexParameters().Any()) + { + return null; + } + + + if (TypeHelper.IsTypeAssignableFrom(propertyInfo.PropertyType)) + { + return new ClonePropertyInfo(propertyInfo) { IsDeepCloneable = true }; + } + + if (TypeHelper.IsTypeAssignableFrom(propertyInfo.PropertyType) + && TypeHelper.IsTypeAssignableFrom(propertyInfo.PropertyType) == false) + { + if (propertyInfo.PropertyType.IsGenericType + && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>) + || propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>) + || propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))) + { + //if it is a IEnumerable<>, IList or ICollection<> we'll use a List<> + var genericType = typeof(List<>).MakeGenericType(propertyInfo.PropertyType.GetGenericArguments()); + return new ClonePropertyInfo(propertyInfo) { GenericListType = genericType }; + } + if (propertyInfo.PropertyType.IsArray + || (propertyInfo.PropertyType.IsInterface && propertyInfo.PropertyType.IsGenericType == false)) + { + //if its an array, we'll create a list to work with first and then convert to array later + //otherwise if its just a regular derivitave of IEnumerable, we can use a list too + return new ClonePropertyInfo(propertyInfo) { GenericListType = typeof(List) }; + } + //skip instead of trying to create instance of abstract or interface + if (propertyInfo.PropertyType.IsAbstract || propertyInfo.PropertyType.IsInterface) + { + return null; + } + + //its a custom IEnumerable, we'll try to create it + try + { + var custom = Activator.CreateInstance(propertyInfo.PropertyType); + //if it's an IList we can work with it, otherwise we cannot + var newList = custom as IList; + if (newList == null) + { + return null; + } + return new ClonePropertyInfo(propertyInfo) {GenericListType = propertyInfo.PropertyType}; + } + catch (Exception) + { + //could not create this type so we'll skip it + return null; + } + } + return new ClonePropertyInfo(propertyInfo); + }) + .Where(x => x.HasValue) + .Select(x => x.Value) .ToArray()); - foreach (var propertyInfo in refProperties) + foreach (var clonePropertyInfo in refProperties) { - if (TypeHelper.IsTypeAssignableFrom(propertyInfo.PropertyType)) + if (clonePropertyInfo.IsDeepCloneable) { //this ref property is also deep cloneable so clone it - var result = (IDeepCloneable)propertyInfo.GetValue(input, null); + var result = (IDeepCloneable)clonePropertyInfo.PropertyInfo.GetValue(input, null); if (result != null) { //set the cloned value to the property - propertyInfo.SetValue(output, result.DeepClone(), null); + clonePropertyInfo.PropertyInfo.SetValue(output, result.DeepClone(), null); } } - else if (TypeHelper.IsTypeAssignableFrom(propertyInfo.PropertyType) - && TypeHelper.IsTypeAssignableFrom(propertyInfo.PropertyType) == false) + else if (clonePropertyInfo.IsList) { - IList newList; - if (propertyInfo.PropertyType.IsGenericType - && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>) - || propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>) - || propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))) - { - //if it is a IEnumerable<>, IList or ICollection<> we'll use a List<> - var genericType = typeof(List<>).MakeGenericType(propertyInfo.PropertyType.GetGenericArguments()); - newList = (IList)Activator.CreateInstance(genericType); - } - else if (propertyInfo.PropertyType.IsArray - || (propertyInfo.PropertyType.IsInterface && propertyInfo.PropertyType.IsGenericType == false)) - { - //if its an array, we'll create a list to work with first and then convert to array later - //otherwise if its just a regular derivitave of IEnumerable, we can use a list too - newList = new List(); - } - else - { - //skip instead of trying to create instance of abstract or interface - if (propertyInfo.PropertyType.IsAbstract || propertyInfo.PropertyType.IsInterface) - { - continue; - } - - //its a custom IEnumerable, we'll try to create it - try - { - var custom = Activator.CreateInstance(propertyInfo.PropertyType); - //if it's an IList we can work with it, otherwise we cannot - newList = custom as IList; - if (newList == null) - { - continue; - } - } - catch (Exception) - { - //could not create this type so we'll skip it - continue; - } - } - - var enumerable = (IEnumerable)propertyInfo.GetValue(input, null); + var enumerable = (IEnumerable)clonePropertyInfo.PropertyInfo.GetValue(input, null); if (enumerable == null) continue; + var newList = (IList)Activator.CreateInstance(clonePropertyInfo.GenericListType); + var isUsableType = true; //now clone each item @@ -136,21 +174,21 @@ namespace Umbraco.Core.Models continue; } - if (propertyInfo.PropertyType.IsArray) + if (clonePropertyInfo.PropertyInfo.PropertyType.IsArray) { //need to convert to array - var arr = (object[])Activator.CreateInstance(propertyInfo.PropertyType, newList.Count); + var arr = (object[])Activator.CreateInstance(clonePropertyInfo.PropertyInfo.PropertyType, newList.Count); for (int i = 0; i < newList.Count; i++) { arr[i] = newList[i]; } //set the cloned collection - propertyInfo.SetValue(output, arr, null); + clonePropertyInfo.PropertyInfo.SetValue(output, arr, null); } else { //set the cloned collection - propertyInfo.SetValue(output, newList, null); + clonePropertyInfo.PropertyInfo.SetValue(output, newList, null); } } diff --git a/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs b/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs index 3cff4f0298..5f30c08ce7 100644 --- a/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs +++ b/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs @@ -98,10 +98,45 @@ namespace Umbraco.Core.Models.PublishedContent #endregion - + #region Cache + + // these methods are called by ContentTypeCacheRefresher and DataTypeCacheRefresher + + internal static void ClearAll() + { + Logging.LogHelper.Debug("Clear all."); + // ok and faster to do it by types, assuming noone else caches PublishedContentType instances + //ApplicationContext.Current.ApplicationCache.ClearStaticCacheByKeySearch("PublishedContentType_"); + ApplicationContext.Current.ApplicationCache.StaticCache.ClearCacheObjectTypes(); + } + + internal static void ClearContentType(int id) + { + Logging.LogHelper.Debug("Clear content type w/id {0}.", () => id); + // requires a predicate because the key does not contain the ID + // faster than key strings comparisons anyway + ApplicationContext.Current.ApplicationCache.StaticCache.ClearCacheObjectTypes( + (key, value) => value.Id == id); + } + + internal static void ClearDataType(int id) + { + Logging.LogHelper.Debug("Clear data type w/id {0}.", () => id); + // there is no recursion to handle here because a PublishedContentType contains *all* its + // properties ie both its own properties and those that were inherited (it's based upon an + // IContentTypeComposition) and so every PublishedContentType having a property based upon + // the cleared data type, be it local or inherited, will be cleared. + ApplicationContext.Current.ApplicationCache.StaticCache.ClearCacheObjectTypes( + (key, value) => value.PropertyTypes.Any(x => x.DataTypeId == id)); + } + public static PublishedContentType Get(PublishedItemType itemType, string alias) { - var type = CreatePublishedContentType(itemType, alias); + var key = string.Format("PublishedContentType_{0}_{1}", + itemType.ToString().ToLowerInvariant(), alias.ToLowerInvariant()); + + var type = ApplicationContext.Current.ApplicationCache.StaticCache.GetCacheItem(key, + () => CreatePublishedContentType(itemType, alias)); return type; } @@ -134,8 +169,21 @@ namespace Umbraco.Core.Models.PublishedContent return new PublishedContentType(contentType); } - // for unit tests - internal static Func GetPublishedContentTypeCallback { get; set; } - + // for unit tests - changing the callback must reset the cache obviously + private static Func _getPublishedContentTypeCallBack; + internal static Func GetPublishedContentTypeCallback + { + get { return _getPublishedContentTypeCallBack; } + set + { + // see note above + //ClearAll(); + ApplicationContext.Current.ApplicationCache.StaticCache.ClearCacheByKeySearch("PublishedContentType_"); + + _getPublishedContentTypeCallBack = value; + } + } + + #endregion } } diff --git a/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyType.cs b/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyType.cs index f4b1597a7d..22d453e150 100644 --- a/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyType.cs +++ b/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyType.cs @@ -230,13 +230,13 @@ namespace Umbraco.Core.Models.PublishedContent { _sourceCacheLevel = converterMeta.GetPropertyCacheLevel(this, PropertyCacheValue.Source); _objectCacheLevel = converterMeta.GetPropertyCacheLevel(this, PropertyCacheValue.Object); - _objectCacheLevel = converterMeta.GetPropertyCacheLevel(this, PropertyCacheValue.XPath); + _xpathCacheLevel = converterMeta.GetPropertyCacheLevel(this, PropertyCacheValue.XPath); } else { _sourceCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Source); _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Object); - _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.XPath); + _xpathCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.XPath); } if (_objectCacheLevel < _sourceCacheLevel) _objectCacheLevel = _sourceCacheLevel; if (_xpathCacheLevel < _sourceCacheLevel) _xpathCacheLevel = _sourceCacheLevel; diff --git a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSeven/UpdateRelatedLinksData.cs b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSeven/UpdateRelatedLinksData.cs index 830adfd7fb..684196c2e6 100644 --- a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSeven/UpdateRelatedLinksData.cs +++ b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSeven/UpdateRelatedLinksData.cs @@ -37,9 +37,9 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSeven if (!dataTypeIds.Any()) return string.Empty; - var propertyData = - database.Fetch( - "WHERE propertyTypeId in (SELECT id from cmsPropertyType where dataTypeID IN (@dataTypeIds))", new { dataTypeIds = dataTypeIds }); + // need to use dynamic, as PropertyDataDto has new properties + var propertyData = database.Fetch("SELECT * FROM cmsPropertyData" + + " WHERE propertyTypeId in (SELECT id from cmsPropertyType where dataTypeID IN (@dataTypeIds))", new { dataTypeIds = dataTypeIds }); if (!propertyData.Any()) return string.Empty; var nodesIdsWithProperty = propertyData.Select(x => x.NodeId).Distinct().ToArray(); @@ -71,13 +71,16 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSeven xml = new XmlDocument(); xml.LoadXml(data.Text); } - catch (Exception ex) + catch (Exception ex) { - Logger.Error("The data stored for property id " + data.Id + " on document " + data.NodeId + - " is not valid XML, the data will be removed because it cannot be converted to the new format. The value was: " + data.Text, ex); + int dataId = data.id; + int dataNodeId = data.nodeId; + string dataText = data.dataNText; + Logger.Error("The data stored for property id " + dataId + " on document " + dataNodeId + + " is not valid XML, the data will be removed because it cannot be converted to the new format. The value was: " + dataText, ex); - data.Text = ""; - database.Update(data); + data.dataNText = ""; + database.Update("cmsPropertyData", "id", data, new[] { "dataNText" }); UpdateXmlTable(propertyTypes, data, cmsContentXmlEntries, database); @@ -91,11 +94,11 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSeven { var title = node.Attributes["title"].Value; var type = node.Attributes["type"].Value; - var newwindow = node.Attributes["newwindow"].Value.Equals("1") ? true : false; + var newwindow = node.Attributes["newwindow"].Value.Equals("1"); var lnk = node.Attributes["link"].Value; //create the links in the format the new prop editor expects it to be - var link = new ExpandoObject() as IDictionary; + var link = new ExpandoObject() as IDictionary; link.Add("title", title); link.Add("caption", title); link.Add("link", lnk); @@ -110,9 +113,9 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSeven } //store the serialized data - data.Text = JsonConvert.SerializeObject(links); + data.dataNText = JsonConvert.SerializeObject(links); - database.Update(data); + database.Update("cmsPropertyData", "id", data, new[] { "dataNText" }); UpdateXmlTable(propertyTypes, data, cmsContentXmlEntries, database); diff --git a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourZero/AddUniqueIdPropertyTypeGroupColumn.cs b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourZero/AddUniqueIdPropertyTypeGroupColumn.cs index 2a164b6e0d..fe600f6b69 100644 --- a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourZero/AddUniqueIdPropertyTypeGroupColumn.cs +++ b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourZero/AddUniqueIdPropertyTypeGroupColumn.cs @@ -1,4 +1,6 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.Linq; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; @@ -33,45 +35,57 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenFourZer // fill in the data in a way that is consistent over all environments // (ie cannot use random guids, http://issues.umbraco.org/issue/U4-6942) + Execute.Code(UpdateGuids); + } + } - foreach (var data in Context.Database.Query(@" + private static string UpdateGuids(Database database) + { + var updates = new List>(); + + foreach (var data in database.Query(@" SELECT cmsPropertyTypeGroup.id grId, cmsPropertyTypeGroup.text grName, cmsContentType.alias ctAlias, umbracoNode.nodeObjectType nObjType FROM cmsPropertyTypeGroup INNER JOIN cmsContentType ON cmsPropertyTypeGroup.contentTypeNodeId = cmsContentType.nodeId INNER JOIN umbracoNode ON cmsContentType.nodeId = umbracoNode.id")) + { + Guid guid; + // see BaseDataCreation... built-in groups have their own guids + if (data.grId == 3) { - Guid guid; - // see BaseDataCreation... built-in groups have their own guids - if (data.grId == 3) - { - guid = new Guid(Constants.PropertyTypeGroups.Image); - } - else if (data.grId == 4) - { - guid = new Guid(Constants.PropertyTypeGroups.File); - } - else if (data.grId == 5) - { - guid = new Guid(Constants.PropertyTypeGroups.Contents); - } - else if (data.grId == 11) - { - guid = new Guid(Constants.PropertyTypeGroups.Membership); - } - else - { - // create a consistent guid from - // group name + content type alias + object type - string guidSource = data.grName + data.ctAlias + data.nObjType; - guid = guidSource.ToGuid(); - } - - // set the Unique Id to the one we've generated - Update.Table("cmsPropertyTypeGroup").Set(new { uniqueID = guid }).Where(new { id = data.grId }); + guid = new Guid(Constants.PropertyTypeGroups.Image); } + else if (data.grId == 4) + { + guid = new Guid(Constants.PropertyTypeGroups.File); + } + else if (data.grId == 5) + { + guid = new Guid(Constants.PropertyTypeGroups.Contents); + } + else if (data.grId == 11) + { + guid = new Guid(Constants.PropertyTypeGroups.Membership); + } + else + { + // create a consistent guid from + // group name + content type alias + object type + string guidSource = data.grName + data.ctAlias + data.nObjType; + guid = guidSource.ToGuid(); + } + + // set the Unique Id to the one we've generated + // but not within the foreach loop (as we already have a data reader open) + updates.Add(Tuple.Create(guid, data.grId)); } + + foreach (var update in updates) + database.Execute("UPDATE cmsPropertyTypeGroup SET uniqueID=@uid WHERE id=@id", new { uid = update.Item1, id = update.Item2 }); + + return string.Empty; } public override void Down() diff --git a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSixZeroOne/UpdatePropertyTypesAndGroups.cs b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSixZeroOne/UpdatePropertyTypesAndGroups.cs index ff71aec142..32c81700a8 100644 --- a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSixZeroOne/UpdatePropertyTypesAndGroups.cs +++ b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSixZeroOne/UpdatePropertyTypesAndGroups.cs @@ -33,36 +33,40 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSixZeroOne // won't exist yet var propertyTypes = database.Fetch("SELECT * FROM cmsPropertyType WHERE propertyTypeGroupId > 0"); - var propertyGroups = database.Fetch("WHERE id > 0"); + // need to use dynamic, as PropertyTypeGroupDto has new properties + var propertyGroups = database.Fetch("SELECT * FROM cmsPropertyTypeGroup WHERE id > 0"); foreach (var propertyType in propertyTypes) { // get the PropertyTypeGroup of the current PropertyType, skip if not found - var propertyTypeGroup = propertyGroups.FirstOrDefault(x => x.Id == propertyType.propertyTypeGroupId); + var propertyTypeGroup = propertyGroups.FirstOrDefault(x => x.id == propertyType.propertyTypeGroupId); if (propertyTypeGroup == null) continue; // if the PropretyTypeGroup belongs to the same content type as the PropertyType, then fine - if (propertyTypeGroup.ContentTypeNodeId == propertyType.contentTypeId) continue; + if (propertyTypeGroup.contenttypeNodeId == propertyType.contentTypeId) continue; // else we want to assign the PropertyType to a proper PropertyTypeGroup // ie one that does belong to the same content - look for it var okPropertyTypeGroup = propertyGroups.FirstOrDefault(x => - x.Text == propertyTypeGroup.Text && // same name - x.ContentTypeNodeId == propertyType.contentTypeId); // but for proper content type + x.text == propertyTypeGroup.text && // same name + x.contenttypeNodeId == propertyType.contentTypeId); // but for proper content type if (okPropertyTypeGroup == null) { - // does not exist, create a new PropertyTypeGroup, - var propertyGroup = new PropertyTypeGroupDto + // does not exist, create a new PropertyTypeGroup + // cannot use a PropertyTypeGroupDto because of the new (not-yet-existing) uniqueID property + // cannot use a dynamic because database.Insert fails to set the value of property + var propertyGroup = new PropertyTypeGroupDtoTemp { - ContentTypeNodeId = propertyType.contentTypeId, - Text = propertyTypeGroup.Text, - SortOrder = propertyTypeGroup.SortOrder + id = 0, + contenttypeNodeId = propertyType.contentTypeId, + text = propertyTypeGroup.text, + sortorder = propertyTypeGroup.sortorder }; // save + add to list of groups - int id = Convert.ToInt16(database.Insert(propertyGroup)); - propertyGroup.Id = id; + int id = Convert.ToInt16(database.Insert("cmsPropertyTypeGroup", "id", propertyGroup)); + propertyGroup.id = id; propertyGroups.Add(propertyGroup); // update the PropertyType to use the new PropertyTypeGroup @@ -71,7 +75,7 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSixZeroOne else { // exists, update PropertyType to use the PropertyTypeGroup - propertyType.propertyTypeGroupId = okPropertyTypeGroup.Id; + propertyType.propertyTypeGroupId = okPropertyTypeGroup.id; } database.Update("cmsPropertyType", "id", propertyType); } @@ -79,5 +83,13 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSixZeroOne return string.Empty; } + + private class PropertyTypeGroupDtoTemp + { + public int id { get; set; } + public int contenttypeNodeId { get; set; } + public string text { get; set; } + public int sortorder { get; set; } + } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Persistence/PetaPoco.cs b/src/Umbraco.Core/Persistence/PetaPoco.cs index d55ad8fc14..88f90639d1 100644 --- a/src/Umbraco.Core/Persistence/PetaPoco.cs +++ b/src/Umbraco.Core/Persistence/PetaPoco.cs @@ -834,7 +834,7 @@ namespace Umbraco.Core.Persistence var pd = PocoData.ForType(typeof(T)); try { - r = cmd.ExecuteReader(); + r = cmd.ExecuteReaderWithRetry(); OnExecutedCommand(cmd); } catch (Exception x) diff --git a/src/Umbraco.Core/Persistence/Repositories/ContentRepository.cs b/src/Umbraco.Core/Persistence/Repositories/ContentRepository.cs index 1f5cc1ecd4..7d3557a81d 100644 --- a/src/Umbraco.Core/Persistence/Repositories/ContentRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/ContentRepository.cs @@ -689,8 +689,7 @@ namespace Umbraco.Core.Persistence.Repositories public int CountPublished() { var sql = GetBaseQuery(true).Where(x => x.Trashed == false) - .Where(x => x.Published == true) - .Where(x => x.Newest == true); + .Where(x => x.Published == true); return Database.ExecuteScalar(sql); } diff --git a/src/Umbraco.Core/Persistence/Repositories/ContentTypeBaseRepository.cs b/src/Umbraco.Core/Persistence/Repositories/ContentTypeBaseRepository.cs index cf1fbcc71f..907f66435e 100644 --- a/src/Umbraco.Core/Persistence/Repositories/ContentTypeBaseRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/ContentTypeBaseRepository.cs @@ -32,12 +32,12 @@ namespace Umbraco.Core.Persistence.Repositories { protected ContentTypeBaseRepository(IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) - { + { } - + public IEnumerable> Move(TEntity toMove, EntityContainer container) { - var parentId = -1; + var parentId = Constants.System.Root; if (container != null) { // Check on paths @@ -54,33 +54,32 @@ namespace Umbraco.Core.Persistence.Repositories new MoveEventInfo(toMove, toMove.Path, parentId) }; - var origPath = toMove.Path; - //do the move to a new parent + // get the level delta (old pos to new pos) + var levelDelta = container == null + ? 1 - toMove.Level + : container.Level + 1 - toMove.Level; + + // move to parent (or -1), update path, save toMove.ParentId = parentId; - - //set the updated path - toMove.Path = string.Concat(container == null ? parentId.ToInvariantString() : container.Path, ",", toMove.Id); - - //schedule it for updating in the transaction + var toMovePath = toMove.Path + ","; // save before changing + toMove.Path = (container == null ? Constants.System.Root.ToString() : container.Path) + "," + toMove.Id; + toMove.Level = container == null ? 1 : container.Level + 1; AddOrUpdate(toMove); //update all descendants, update in order of level - var descendants = this.GetByQuery( - new Query().Where(type => type.Path.StartsWith(origPath + ","))); + var descendants = GetByQuery(new Query().Where(type => type.Path.StartsWith(toMovePath))); + var paths = new Dictionary(); + paths[toMove.Id] = toMove.Path; - var lastParent = toMove; foreach (var descendant in descendants.OrderBy(x => x.Level)) { moveInfo.Add(new MoveEventInfo(descendant, descendant.Path, descendant.ParentId)); - descendant.ParentId = lastParent.Id; - descendant.Path = string.Concat(lastParent.Path, ",", descendant.Id); + descendant.Path = paths[descendant.Id] = paths[descendant.ParentId] + "," + descendant.Id; + descendant.Level += levelDelta; - //schedule it for updating in the transaction AddOrUpdate(descendant); - - lastParent = descendant; } return moveInfo; @@ -286,7 +285,7 @@ AND umbracoNode.id <> @id", { //Find PropertyTypes for the removed ContentType var propertyTypes = Database.Fetch("WHERE contentTypeId = @Id", new { Id = key }); - //Loop through the Content that is based on the current ContentType in order to remove the Properties that are + //Loop through the Content that is based on the current ContentType in order to remove the Properties that are //based on the PropertyTypes that belong to the removed ContentType. foreach (var contentDto in contentDtos) { @@ -410,7 +409,7 @@ AND umbracoNode.id <> @id", AssignDataTypeFromPropertyEditor(propertyType); } - //validate the alias! + //validate the alias! ValidateAlias(propertyType); var propertyTypeDto = propertyGroupFactory.BuildPropertyTypeDto(tabId, propertyType); @@ -647,17 +646,14 @@ AND umbracoNode.id <> @id", var allParentIdsAsArray = allParentContentTypeIds.SelectMany(x => x.Value).Distinct().ToArray(); if (allParentIdsAsArray.Any()) { - //NO!!!!!!!!!!! Do not recurse lookup, we've already looked them all up - //var allParentContentTypes = contentTypeRepository.GetAll(allParentIdsAsArray).ToArray(); - var allParentContentTypes = contentTypes.Where(x => allParentIdsAsArray.Contains(x.Id)).ToArray(); foreach (var contentType in contentTypes) - { + { var entityId = contentType.Id; var parentContentTypes = allParentContentTypes.Where(x => - { + { var parentEntityId = x.Id; return allParentContentTypeIds[entityId].Contains(parentEntityId); @@ -665,7 +661,7 @@ AND umbracoNode.id <> @id", foreach (var parentContentType in parentContentTypes) { var result = contentType.AddContentType(parentContentType); - //Do something if adding fails? (Should hopefully not be possible unless someone created a circular reference) + //Do something if adding fails? (Should hopefully not be possible unless someone created a circular reference) } //on initial construction we don't want to have dirty properties tracked @@ -701,7 +697,7 @@ AND umbracoNode.id <> @id", foreach (var contentType in contentTypes) { var entityId = contentType.Id; - + var associatedTemplateIds = associatedTemplates[entityId].Select(x => x.TemplateId) .Distinct() .ToArray(); @@ -716,9 +712,9 @@ AND umbracoNode.id <> @id", internal static IEnumerable MapMediaTypes(Database db, ISqlSyntaxProvider sqlSyntax, out IDictionary> parentMediaTypeIds) - { - Mandate.ParameterNotNull(db, "db"); - + { + Mandate.ParameterNotNull(db, "db"); + var sql = @"SELECT cmsContentType.pk as ctPk, cmsContentType.alias as ctAlias, cmsContentType.allowAtRoot as ctAllowAtRoot, cmsContentType.description as ctDesc, cmsContentType.icon as ctIcon, cmsContentType.isContainer as ctIsContainer, cmsContentType.nodeId as ctId, cmsContentType.thumbnail as ctThumb, AllowedTypes.AllowedId as ctaAllowedId, AllowedTypes.SortOrder as ctaSortOrder, AllowedTypes.alias as ctaAlias, @@ -730,19 +726,19 @@ AND umbracoNode.id <> @id", INNER JOIN umbracoNode ON cmsContentType.nodeId = umbracoNode.id LEFT JOIN ( - SELECT cmsContentTypeAllowedContentType.Id, cmsContentTypeAllowedContentType.AllowedId, cmsContentType.alias, cmsContentTypeAllowedContentType.SortOrder - FROM cmsContentTypeAllowedContentType + SELECT cmsContentTypeAllowedContentType.Id, cmsContentTypeAllowedContentType.AllowedId, cmsContentType.alias, cmsContentTypeAllowedContentType.SortOrder + FROM cmsContentTypeAllowedContentType INNER JOIN cmsContentType ON cmsContentTypeAllowedContentType.AllowedId = cmsContentType.nodeId ) AllowedTypes ON AllowedTypes.Id = cmsContentType.nodeId LEFT JOIN ( SELECT cmsContentType2ContentType.parentContentTypeId, umbracoNode.uniqueID AS parentContentTypeKey, cmsContentType2ContentType.childContentTypeId - FROM cmsContentType2ContentType + FROM cmsContentType2ContentType INNER JOIN umbracoNode ON cmsContentType2ContentType.parentContentTypeId = umbracoNode." + sqlSyntax.GetQuotedColumnName("id") + @" - ) ParentTypes - ON ParentTypes.childContentTypeId = cmsContentType.nodeId + ) ParentTypes + ON ParentTypes.childContentTypeId = cmsContentType.nodeId WHERE (umbracoNode.nodeObjectType = @nodeObjectType) ORDER BY ctId"; @@ -762,10 +758,11 @@ AND umbracoNode.id <> @id", // we used to do. var queue = new Queue(result); var currAllowedContentTypes = new List(); + while (queue.Count > 0) { var ct = queue.Dequeue(); - + //check for allowed content types int? allowedCtId = ct.ctaAllowedId; int? allowedCtSort = ct.ctaSortOrder; @@ -801,7 +798,7 @@ AND umbracoNode.id <> @id", //Here we need to reset the current variables, we're now collecting data for a different content type currAllowedContentTypes = new List(); } - } + } return mappedMediaTypes; } @@ -864,7 +861,7 @@ AND umbracoNode.id <> @id", ParentTypes.parentContentTypeId as chtParentId,ParentTypes.parentContentTypeKey as chtParentKey, umbracoNode.createDate as nCreateDate, umbracoNode." + sqlSyntax.GetQuotedColumnName("level") + @" as nLevel, umbracoNode.nodeObjectType as nObjectType, umbracoNode.nodeUser as nUser, umbracoNode.parentID as nParentId, umbracoNode." + sqlSyntax.GetQuotedColumnName("path") + @" as nPath, umbracoNode.sortOrder as nSortOrder, umbracoNode." + sqlSyntax.GetQuotedColumnName("text") + @" as nName, umbracoNode.trashed as nTrashed, - umbracoNode.uniqueID as nUniqueId, + umbracoNode.uniqueID as nUniqueId, Template.alias as tAlias, Template.nodeId as tId,Template.text as tText FROM cmsContentType INNER JOIN umbracoNode @@ -872,8 +869,8 @@ AND umbracoNode.id <> @id", LEFT JOIN cmsDocumentType ON cmsDocumentType.contentTypeNodeId = cmsContentType.nodeId LEFT JOIN ( - SELECT cmsContentTypeAllowedContentType.Id, cmsContentTypeAllowedContentType.AllowedId, cmsContentType.alias, cmsContentTypeAllowedContentType.SortOrder - FROM cmsContentTypeAllowedContentType + SELECT cmsContentTypeAllowedContentType.Id, cmsContentTypeAllowedContentType.AllowedId, cmsContentType.alias, cmsContentTypeAllowedContentType.SortOrder + FROM cmsContentTypeAllowedContentType INNER JOIN cmsContentType ON cmsContentTypeAllowedContentType.AllowedId = cmsContentType.nodeId ) AllowedTypes @@ -886,14 +883,14 @@ AND umbracoNode.id <> @id", ON Template.nodeId = cmsDocumentType.templateNodeId LEFT JOIN ( SELECT cmsContentType2ContentType.parentContentTypeId, umbracoNode.uniqueID AS parentContentTypeKey, cmsContentType2ContentType.childContentTypeId - FROM cmsContentType2ContentType + FROM cmsContentType2ContentType INNER JOIN umbracoNode ON cmsContentType2ContentType.parentContentTypeId = umbracoNode." + sqlSyntax.GetQuotedColumnName("id") + @" - ) ParentTypes - ON ParentTypes.childContentTypeId = cmsContentType.nodeId + ) ParentTypes + ON ParentTypes.childContentTypeId = cmsContentType.nodeId WHERE (umbracoNode.nodeObjectType = @nodeObjectType) ORDER BY ctId"; - + var result = db.Fetch(sql, new { nodeObjectType = new Guid(Constants.ObjectTypes.DocumentType)}); if (result.Any() == false) @@ -907,7 +904,7 @@ AND umbracoNode.id <> @id", associatedTemplates = new Dictionary>(); var mappedContentTypes = new List(); - var queue = new Queue(result); + var queue = new Queue(result); var currDefaultTemplate = -1; var currAllowedContentTypes = new List(); while (queue.Count > 0) @@ -1053,14 +1050,14 @@ AND umbracoNode.id <> @id", // therefore the union of the two contains all of the property type and property group information we need // NOTE: MySQL requires a SELECT * FROM the inner union in order to be able to sort . lame. - var sqlBuilder = new StringBuilder(@"SELECT PG.contenttypeNodeId as contentTypeId, - PT.ptUniqueId as ptUniqueID, PT.ptId, PT.ptAlias, PT.ptDesc,PT.ptMandatory,PT.ptName,PT.ptSortOrder,PT.ptRegExp, + var sqlBuilder = new StringBuilder(@"SELECT PG.contenttypeNodeId as contentTypeId, + PT.ptUniqueId as ptUniqueID, PT.ptId, PT.ptAlias, PT.ptDesc,PT.ptMandatory,PT.ptName,PT.ptSortOrder,PT.ptRegExp, PT.dtId,PT.dtDbType,PT.dtPropEdAlias, PG.id as pgId, PG.uniqueID as pgKey, PG.sortorder as pgSortOrder, PG." + sqlSyntax.GetQuotedColumnName("text") + @" as pgText FROM cmsPropertyTypeGroup as PG LEFT JOIN ( - SELECT PT.uniqueID as ptUniqueId, PT.id as ptId, PT.Alias as ptAlias, PT." + sqlSyntax.GetQuotedColumnName("Description") + @" as ptDesc, + SELECT PT.uniqueID as ptUniqueId, PT.id as ptId, PT.Alias as ptAlias, PT." + sqlSyntax.GetQuotedColumnName("Description") + @" as ptDesc, PT.mandatory as ptMandatory, PT.Name as ptName, PT.sortOrder as ptSortOrder, PT.validationRegExp as ptRegExp, PT.propertyTypeGroupId as ptGroupId, DT.dbType as dtDbType, DT.nodeId as dtId, DT.propertyEditorAlias as dtPropEdAlias @@ -1070,11 +1067,11 @@ AND umbracoNode.id <> @id", ) as PT ON PT.ptGroupId = PG.id WHERE (PG.contenttypeNodeId in (@contentTypeIds)) - + UNION SELECT PT.contentTypeId as contentTypeId, - PT.uniqueID as ptUniqueID, PT.id as ptId, PT.Alias as ptAlias, PT." + sqlSyntax.GetQuotedColumnName("Description") + @" as ptDesc, + PT.uniqueID as ptUniqueID, PT.id as ptId, PT.Alias as ptAlias, PT." + sqlSyntax.GetQuotedColumnName("Description") + @" as ptDesc, PT.mandatory as ptMandatory, PT.Name as ptName, PT.sortOrder as ptSortOrder, PT.validationRegExp as ptRegExp, DT.nodeId as dtId, DT.dbType as dtDbType, DT.propertyEditorAlias as dtPropEdAlias, PG.id as pgId, PG.uniqueID as pgKey, PG.sortorder as pgSortOrder, PG." + sqlSyntax.GetQuotedColumnName("text") + @" as pgText diff --git a/src/Umbraco.Core/Persistence/Repositories/ContentTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/ContentTypeRepository.cs index 1c67aa0cf5..b7b4ddd583 100644 --- a/src/Umbraco.Core/Persistence/Repositories/ContentTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/ContentTypeRepository.cs @@ -37,7 +37,10 @@ namespace Umbraco.Core.Persistence.Repositories get { //Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection - return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory(RuntimeCache, GetEntityId)); + return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory( + RuntimeCache, GetEntityId, () => PerformGetAll(), + //allow this cache to expire + expires:true)); } } @@ -63,13 +66,17 @@ namespace Umbraco.Core.Persistence.Repositories { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator(sqlClause, query); - var sql = translator.Translate() - .OrderBy(x => x.Text, SqlSyntax); + var sql = translator.Translate(); var dtos = Database.Fetch(sql); - return dtos.Any() - ? GetAll(dtos.DistinctBy(x => x.ContentTypeDto.NodeId).Select(x => x.ContentTypeDto.NodeId).ToArray()) - : Enumerable.Empty(); + + return + //This returns a lookup from the GetAll cached looup + (dtos.Any() + ? GetAll(dtos.DistinctBy(x => x.ContentTypeDto.NodeId).Select(x => x.ContentTypeDto.NodeId).ToArray()) + : Enumerable.Empty()) + //order the result by name + .OrderBy(x => x.Name); } /// diff --git a/src/Umbraco.Core/Persistence/Repositories/DomainRepository.cs b/src/Umbraco.Core/Persistence/Repositories/DomainRepository.cs index 563243f12c..7b6cc162a8 100644 --- a/src/Umbraco.Core/Persistence/Repositories/DomainRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/DomainRepository.cs @@ -29,7 +29,8 @@ namespace Umbraco.Core.Persistence.Repositories get { //Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection - return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory(RuntimeCache, GetEntityId)); + return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory( + RuntimeCache, GetEntityId, () => PerformGetAll(), false)); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/LanguageRepository.cs b/src/Umbraco.Core/Persistence/Repositories/LanguageRepository.cs index 3884eac888..f9a8e59cfa 100644 --- a/src/Umbraco.Core/Persistence/Repositories/LanguageRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/LanguageRepository.cs @@ -30,7 +30,8 @@ namespace Umbraco.Core.Persistence.Repositories get { //Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection - return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory(RuntimeCache, GetEntityId)); + return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory( + RuntimeCache, GetEntityId, () => PerformGetAll(), false)); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/MediaTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/MediaTypeRepository.cs index 86c0927664..50a89bfd65 100644 --- a/src/Umbraco.Core/Persistence/Repositories/MediaTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/MediaTypeRepository.cs @@ -34,7 +34,10 @@ namespace Umbraco.Core.Persistence.Repositories get { //Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection - return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory(RuntimeCache, GetEntityId)); + return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory( + RuntimeCache, GetEntityId, () => PerformGetAll(), + //allow this cache to expire + expires: true)); } } @@ -60,13 +63,17 @@ namespace Umbraco.Core.Persistence.Repositories { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator(sqlClause, query); - var sql = translator.Translate() - .OrderBy(x => x.Text, SqlSyntax); + var sql = translator.Translate(); var dtos = Database.Fetch(sql); - return dtos.Any() - ? GetAll(dtos.DistinctBy(x => x.NodeId).Select(x => x.NodeId).ToArray()) - : Enumerable.Empty(); + + return + //This returns a lookup from the GetAll cached looup + (dtos.Any() + ? GetAll(dtos.DistinctBy(x => x.NodeId).Select(x => x.NodeId).ToArray()) + : Enumerable.Empty()) + //order the result by name + .OrderBy(x => x.Name); } /// diff --git a/src/Umbraco.Core/Persistence/Repositories/MemberTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/MemberTypeRepository.cs index 581ca3c4a6..b35c793400 100644 --- a/src/Umbraco.Core/Persistence/Repositories/MemberTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/MemberTypeRepository.cs @@ -33,7 +33,10 @@ namespace Umbraco.Core.Persistence.Repositories get { //Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection - return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory(RuntimeCache, GetEntityId)); + return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory( + RuntimeCache, GetEntityId, () => PerformGetAll(), + //allow this cache to expire + expires: true)); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/PublicAccessRepository.cs b/src/Umbraco.Core/Persistence/Repositories/PublicAccessRepository.cs index 1d8e56190b..22fad9d99b 100644 --- a/src/Umbraco.Core/Persistence/Repositories/PublicAccessRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/PublicAccessRepository.cs @@ -26,7 +26,8 @@ namespace Umbraco.Core.Persistence.Repositories get { //Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection - return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory(RuntimeCache, GetEntityId)); + return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory( + RuntimeCache, GetEntityId, () => PerformGetAll(), false)); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/TemplateRepository.cs b/src/Umbraco.Core/Persistence/Repositories/TemplateRepository.cs index 3545bc1c55..fa780e1bd0 100644 --- a/src/Umbraco.Core/Persistence/Repositories/TemplateRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/TemplateRepository.cs @@ -51,7 +51,8 @@ namespace Umbraco.Core.Persistence.Repositories get { //Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection - return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory(RuntimeCache, GetEntityId)); + return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory( + RuntimeCache, GetEntityId, () => PerformGetAll(), false)); } } @@ -488,7 +489,7 @@ namespace Umbraco.Core.Persistence.Repositories var parent = all.FirstOrDefault(x => x.Id == masterTemplateId); if (parent == null) return Enumerable.Empty(); - var children = all.Where(x => x.MasterTemplateAlias == parent.Alias); + var children = all.Where(x => x.MasterTemplateAlias.InvariantEquals(parent.Alias)); return children; } @@ -497,7 +498,7 @@ namespace Umbraco.Core.Persistence.Repositories //return from base.GetAll, this is all cached return base.GetAll().Where(x => alias.IsNullOrWhiteSpace() ? x.MasterTemplateAlias.IsNullOrWhiteSpace() - : x.MasterTemplateAlias == alias); + : x.MasterTemplateAlias.InvariantEquals(alias)); } public IEnumerable GetDescendants(int masterTemplateId) @@ -532,7 +533,7 @@ namespace Umbraco.Core.Persistence.Repositories var descendants = new List(); if (alias.IsNullOrWhiteSpace() == false) { - var parent = all.FirstOrDefault(x => x.Alias == alias); + var parent = all.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); if (parent == null) return Enumerable.Empty(); //recursively add all children AddChildren(all, descendants, parent.Alias); @@ -552,7 +553,7 @@ namespace Umbraco.Core.Persistence.Repositories private void AddChildren(ITemplate[] all, List descendants, string masterAlias) { - var c = all.Where(x => x.MasterTemplateAlias == masterAlias).ToArray(); + var c = all.Where(x => x.MasterTemplateAlias.InvariantEquals(masterAlias)).ToArray(); descendants.AddRange(c); if (c.Any() == false) return; //recurse through all children @@ -573,7 +574,7 @@ namespace Umbraco.Core.Persistence.Repositories //first get all template objects var allTemplates = base.GetAll().ToArray(); - var selfTemplate = allTemplates.SingleOrDefault(x => x.Alias == alias); + var selfTemplate = allTemplates.SingleOrDefault(x => x.Alias.InvariantEquals(alias)); if (selfTemplate == null) { return null; @@ -582,11 +583,11 @@ namespace Umbraco.Core.Persistence.Repositories var top = selfTemplate; while (top.MasterTemplateAlias.IsNullOrWhiteSpace() == false) { - top = allTemplates.Single(x => x.Alias == top.MasterTemplateAlias); + top = allTemplates.Single(x => x.Alias.InvariantEquals(top.MasterTemplateAlias)); } var topNode = new TemplateNode(allTemplates.Single(x => x.Id == top.Id)); - var childTemplates = allTemplates.Where(x => x.MasterTemplateAlias == top.Alias); + var childTemplates = allTemplates.Where(x => x.MasterTemplateAlias.InvariantEquals(top.Alias)); //This now creates the hierarchy recursively topNode.Children = CreateChildren(topNode, childTemplates, allTemplates); @@ -598,7 +599,7 @@ namespace Umbraco.Core.Persistence.Repositories private static TemplateNode WalkTree(TemplateNode current, string alias) { //now walk the tree to find the node - if (current.Template.Alias == alias) + if (current.Template.Alias.InvariantEquals(alias)) { return current; } @@ -730,7 +731,7 @@ namespace Umbraco.Core.Persistence.Repositories //get this node's children var local = childTemplate; - var kids = allTemplates.Where(x => x.MasterTemplateAlias == local.Alias); + var kids = allTemplates.Where(x => x.MasterTemplateAlias.InvariantEquals(local.Alias)); //recurse child.Children = CreateChildren(child, kids, allTemplates); @@ -760,7 +761,7 @@ namespace Umbraco.Core.Persistence.Repositories private bool AliasAlreadExists(ITemplate template) { - var sql = GetBaseQuery(true).Where(x => x.Alias == template.Alias && x.NodeId != template.Id); + var sql = GetBaseQuery(true).Where(x => x.Alias.InvariantEquals(template.Alias) && x.NodeId != template.Id); var count = Database.ExecuteScalar(sql); return count > 0; } diff --git a/src/Umbraco.Core/Persistence/UmbracoDatabase.cs b/src/Umbraco.Core/Persistence/UmbracoDatabase.cs index 9541a1cac0..8fc1150409 100644 --- a/src/Umbraco.Core/Persistence/UmbracoDatabase.cs +++ b/src/Umbraco.Core/Persistence/UmbracoDatabase.cs @@ -12,9 +12,9 @@ namespace Umbraco.Core.Persistence /// Represents the Umbraco implementation of the PetaPoco Database object /// /// - /// Currently this object exists for 'future proofing' our implementation. By having our own inheritied implementation we + /// Currently this object exists for 'future proofing' our implementation. By having our own inheritied implementation we /// can then override any additional execution (such as additional loggging, functionality, etc...) that we need to without breaking compatibility since we'll always be exposing - /// this object instead of the base PetaPoco database object. + /// this object instead of the base PetaPoco database object. /// public class UmbracoDatabase : Database, IDisposeOnRequestEnd { @@ -111,7 +111,9 @@ namespace Umbraco.Core.Persistence public override IDbConnection OnConnectionOpened(IDbConnection connection) { - // wrap the connection with a profiling connection that tracks timings + // propagate timeout if none yet + + // wrap the connection with a profiling connection that tracks timings return new StackExchange.Profiling.Data.ProfiledDbConnection(connection as DbConnection, MiniProfiler.Current); } @@ -121,6 +123,14 @@ namespace Umbraco.Core.Persistence base.OnException(x); } + public override void OnExecutingCommand(IDbCommand cmd) + { + // if no timeout is specified, and the connection has a longer timeout, use it + if (OneTimeCommandTimeout == 0 && CommandTimeout == 0 && cmd.Connection.ConnectionTimeout > 30) + cmd.CommandTimeout = cmd.Connection.ConnectionTimeout; + base.OnExecutingCommand(cmd); + } + public override void OnExecutedCommand(IDbCommand cmd) { if (EnableSqlTrace) diff --git a/src/Umbraco.Core/Profiling/StartupWebProfilerProvider.cs b/src/Umbraco.Core/Profiling/StartupWebProfilerProvider.cs deleted file mode 100644 index 16ce638c0e..0000000000 --- a/src/Umbraco.Core/Profiling/StartupWebProfilerProvider.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System.Threading; -using System.Web; -using StackExchange.Profiling; - -namespace Umbraco.Core.Profiling -{ - /// - /// Allows us to profile items during app startup - before an HttpRequest is created - /// - internal class StartupWebProfilerProvider : WebRequestProfilerProvider - { - public StartupWebProfilerProvider() - { - _startupPhase = StartupPhase.Boot; - //create the startup profiler - _startupProfiler = new MiniProfiler("http://localhost/umbraco-startup", ProfileLevel.Verbose) - { - Name = "StartupProfiler" - }; - } - - private MiniProfiler _startupProfiler; - private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(); - - private enum StartupPhase - { - None = 0, - Boot = 1, - Request = 2 - } - - private volatile StartupPhase _startupPhase; - - public void BootComplete() - { - using (new ReadLock(_locker)) - { - if (_startupPhase != StartupPhase.Boot) return; - } - - using (var l = new UpgradeableReadLock(_locker)) - { - if (_startupPhase == StartupPhase.Boot) - { - l.UpgradeToWriteLock(); - - ////Now we need to transfer some information from our startup phase to the normal - ////web request phase to output the startup profiled information. - ////Stop our internal startup profiler, this will write out it's results to storage. - //StopProfiler(_startupProfiler); - //SaveProfiler(_startupProfiler); - - _startupPhase = StartupPhase.Request; - } - } - } - - public override void Stop(bool discardResults) - { - using (new ReadLock(_locker)) - { - if (_startupPhase == StartupPhase.None) - { - base.Stop(discardResults); - return; - } - } - - using (var l = new UpgradeableReadLock(_locker)) - { - if (_startupPhase > 0 && base.GetCurrentProfiler() == null) - { - l.UpgradeToWriteLock(); - - _startupPhase = StartupPhase.None; - - if (HttpContext.Current != null) - { - HttpContext.Current.Items[":mini-profiler:"] = _startupProfiler; - base.Stop(discardResults); - _startupProfiler = null; - } - } - else - { - base.Stop(discardResults); - } - } - } - - public override MiniProfiler Start(ProfileLevel level) - { - using (new ReadLock(_locker)) - { - if (_startupPhase > 0 && base.GetCurrentProfiler() == null) - { - SetProfilerActive(_startupProfiler); - return _startupProfiler; - } - - return base.Start(level); - } - } - - public override MiniProfiler GetCurrentProfiler() - { - using (new ReadLock(_locker)) - { - if (_startupPhase > 0) - { - try - { - var current = base.GetCurrentProfiler(); - if (current == null) return _startupProfiler; - } - catch - { - return _startupProfiler; - } - } - - return base.GetCurrentProfiler(); - } - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Profiling/WebProfiler.cs b/src/Umbraco.Core/Profiling/WebProfiler.cs index 7e2cf49313..00d088bca7 100644 --- a/src/Umbraco.Core/Profiling/WebProfiler.cs +++ b/src/Umbraco.Core/Profiling/WebProfiler.cs @@ -12,24 +12,15 @@ namespace Umbraco.Core.Profiling /// internal class WebProfiler : IProfiler { - private StartupWebProfilerProvider _startupWebProfilerProvider; /// /// Constructor - /// + /// + /// + /// Binds to application events to enable the MiniProfiler + /// internal WebProfiler() { - //setup some defaults - MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter(); - MiniProfiler.Settings.StackMaxLength = 5000; - - //At this point we know that we've been constructed during app startup, there won't be an HttpRequest in the HttpContext - // since it hasn't started yet. So we need to do some hacking to enable profiling during startup. - _startupWebProfilerProvider = new StartupWebProfilerProvider(); - //this should always be the case during startup, we'll need to set a custom profiler provider - MiniProfiler.Settings.ProfilerProvider = _startupWebProfilerProvider; - - //Binds to application events to enable the MiniProfiler with a real HttpRequest UmbracoApplicationBase.ApplicationInit += UmbracoApplicationApplicationInit; } @@ -62,12 +53,7 @@ namespace Umbraco.Core.Profiling /// void UmbracoApplicationEndRequest(object sender, EventArgs e) { - if (_startupWebProfilerProvider != null) - { - Stop(); - _startupWebProfilerProvider = null; - } - else if (CanPerformProfilingAction(sender)) + if (CanPerformProfilingAction(sender)) { Stop(); } @@ -80,11 +66,6 @@ namespace Umbraco.Core.Profiling /// void UmbracoApplicationBeginRequest(object sender, EventArgs e) { - if (_startupWebProfilerProvider != null) - { - _startupWebProfilerProvider.BootComplete(); - } - if (CanPerformProfilingAction(sender)) { Start(); @@ -143,7 +124,9 @@ namespace Umbraco.Core.Profiling /// Start the profiler /// public void Start() - { + { + MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter(); + MiniProfiler.Settings.StackMaxLength = 5000; MiniProfiler.Start(); } diff --git a/src/Umbraco.Core/Security/AuthenticationExtensions.cs b/src/Umbraco.Core/Security/AuthenticationExtensions.cs index 79fdc1bed1..b8064474bb 100644 --- a/src/Umbraco.Core/Security/AuthenticationExtensions.cs +++ b/src/Umbraco.Core/Security/AuthenticationExtensions.cs @@ -167,74 +167,18 @@ namespace Umbraco.Core.Security /// This clears the forms authentication cookie for webapi since cookies are handled differently /// /// - [Obsolete("Use OWIN IAuthenticationManager.SignOut instead")] + [Obsolete("Use OWIN IAuthenticationManager.SignOut instead", true)] [EditorBrowsable(EditorBrowsableState.Never)] public static void UmbracoLogoutWebApi(this HttpResponseMessage response) { - if (response == null) throw new ArgumentNullException("response"); - //remove the cookie - var authCookie = new CookieHeaderValue(UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName, "") - { - Expires = DateTime.Now.AddYears(-1), - Path = "/" - }; - //remove the preview cookie too - var prevCookie = new CookieHeaderValue(Constants.Web.PreviewCookieName, "") - { - Expires = DateTime.Now.AddYears(-1), - Path = "/" - }; - //remove the external login cookie too - var extLoginCookie = new CookieHeaderValue(Constants.Security.BackOfficeExternalCookieName, "") - { - Expires = DateTime.Now.AddYears(-1), - Path = "/" - }; - - response.Headers.AddCookies(new[] { authCookie, prevCookie, extLoginCookie }); + throw new NotSupportedException("This method is not supported and should not be used, it has been removed in Umbraco 7.4"); } - [Obsolete("Use WebSecurity.SetPrincipalForRequest")] + [Obsolete("Use WebSecurity.SetPrincipalForRequest", true)] [EditorBrowsable(EditorBrowsableState.Never)] public static FormsAuthenticationTicket UmbracoLoginWebApi(this HttpResponseMessage response, IUser user) { - if (response == null) throw new ArgumentNullException("response"); - - //remove the external login cookie - var extLoginCookie = new CookieHeaderValue(Constants.Security.BackOfficeExternalCookieName, "") - { - Expires = DateTime.Now.AddYears(-1), - Path = "/" - }; - - var userDataString = JsonConvert.SerializeObject(Mapper.Map(user)); - - var ticket = new FormsAuthenticationTicket( - 4, - user.Username, - DateTime.Now, - DateTime.Now.AddMinutes(GlobalSettings.TimeOutInMinutes), - true, - userDataString, - "/" - ); - - // Encrypt the cookie using the machine key for secure transport - var encrypted = FormsAuthentication.Encrypt(ticket); - - //add the cookie - var authCookie = new CookieHeaderValue(UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName, encrypted) - { - //Umbraco has always persisted it's original cookie for 1 day so we'll keep it that way - Expires = DateTime.Now.AddMinutes(1440), - Path = "/", - Secure = GlobalSettings.UseSSL, - HttpOnly = true - }; - - response.Headers.AddCookies(new[] { authCookie, extLoginCookie }); - - return ticket; + throw new NotSupportedException("This method is not supported and should not be used, it has been removed in Umbraco 7.4"); } /// diff --git a/src/Umbraco.Core/Security/BackOfficeClaimsIdentityFactory.cs b/src/Umbraco.Core/Security/BackOfficeClaimsIdentityFactory.cs index 8529132bb5..9c46ae69f4 100644 --- a/src/Umbraco.Core/Security/BackOfficeClaimsIdentityFactory.cs +++ b/src/Umbraco.Core/Security/BackOfficeClaimsIdentityFactory.cs @@ -9,6 +9,12 @@ namespace Umbraco.Core.Security { public class BackOfficeClaimsIdentityFactory : ClaimsIdentityFactory { + public BackOfficeClaimsIdentityFactory() + { + SecurityStampClaimType = Constants.Security.SessionIdClaimType; + UserNameClaimType = ClaimTypes.Name; + } + /// /// Create a ClaimsIdentity from a user /// @@ -20,7 +26,7 @@ namespace Umbraco.Core.Security var umbracoIdentity = new UmbracoBackOfficeIdentity(baseIdentity, //set a new session id - new UserData(Guid.NewGuid().ToString("N")) + new UserData { Id = user.Id, Username = user.UserName, @@ -29,7 +35,8 @@ namespace Umbraco.Core.Security Culture = user.Culture, Roles = user.Roles.Select(x => x.RoleId).ToArray(), StartContentNode = user.StartContentId, - StartMediaNode = user.StartMediaId + StartMediaNode = user.StartMediaId, + SessionId = user.SecurityStamp }); return umbracoIdentity; diff --git a/src/Umbraco.Core/Security/MembershipProviderBase.cs b/src/Umbraco.Core/Security/MembershipProviderBase.cs index 392c1545d1..3e02d6aec2 100644 --- a/src/Umbraco.Core/Security/MembershipProviderBase.cs +++ b/src/Umbraco.Core/Security/MembershipProviderBase.cs @@ -759,12 +759,13 @@ namespace Umbraco.Core.Security //This is the correct way to implement this (as per the sql membership provider) - switch ((int)PasswordFormat) + switch (PasswordFormat) { - case 0: + case MembershipPasswordFormat.Clear: return pass; - case 1: + case MembershipPasswordFormat.Hashed: throw new ProviderException("Provider can not decrypt hashed password"); + case MembershipPasswordFormat.Encrypted: default: var bytes = DecryptPassword(Convert.FromBase64String(pass)); return bytes == null ? null : Encoding.Unicode.GetString(bytes, 16, bytes.Length - 16); diff --git a/src/Umbraco.Core/Security/UmbracoBackOfficeIdentity.cs b/src/Umbraco.Core/Security/UmbracoBackOfficeIdentity.cs index 6ce81f3e9f..1bc9902da5 100644 --- a/src/Umbraco.Core/Security/UmbracoBackOfficeIdentity.cs +++ b/src/Umbraco.Core/Security/UmbracoBackOfficeIdentity.cs @@ -209,17 +209,19 @@ namespace Umbraco.Core.Security if (HasClaim(x => x.Type == ClaimTypes.Locality) == false) AddClaim(new Claim(ClaimTypes.Locality, Culture, ClaimValueTypes.String, Issuer, Issuer, this)); - - ////TODO: Not sure why this is null sometimes, it shouldn't be. Somewhere it's not being set - /// I think it's due to some bug I had in chrome, we'll see - //if (UserData.SessionId.IsNullOrWhiteSpace()) - //{ - // UserData.SessionId = Guid.NewGuid().ToString(); - //} - if (HasClaim(x => x.Type == Constants.Security.SessionIdClaimType) == false) + if (HasClaim(x => x.Type == Constants.Security.SessionIdClaimType) == false && SessionId.IsNullOrWhiteSpace() == false) + { AddClaim(new Claim(Constants.Security.SessionIdClaimType, SessionId, ClaimValueTypes.String, Issuer, Issuer, this)); + //The security stamp claim is also required... this is because this claim type is hard coded + // by the SecurityStampValidator, see: https://katanaproject.codeplex.com/workitem/444 + if (HasClaim(x => x.Type == Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType) == false) + { + AddClaim(new Claim(Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType, SessionId, ClaimValueTypes.String, Issuer, Issuer, this)); + } + } + //Add each app as a separate claim if (HasClaim(x => x.Type == Constants.Security.AllowedApplicationsClaimType) == false) { diff --git a/src/Umbraco.Core/Security/UserData.cs b/src/Umbraco.Core/Security/UserData.cs index ff49636217..407d2782dd 100644 --- a/src/Umbraco.Core/Security/UserData.cs +++ b/src/Umbraco.Core/Security/UserData.cs @@ -20,7 +20,7 @@ namespace Umbraco.Core.Security /// Use this constructor to create/assign new UserData to the ticket /// /// - /// A unique id that is assigned to this ticket + /// The security stamp for the user /// public UserData(string sessionId) { @@ -30,8 +30,7 @@ namespace Umbraco.Core.Security } /// - /// This is used to Id the current ticket which we can then use to mitigate csrf attacks - /// and other things that require request validation. + /// This is the 'security stamp' for validation /// [DataMember(Name = "sessionId")] public string SessionId { get; set; } @@ -42,8 +41,6 @@ namespace Umbraco.Core.Security [DataMember(Name = "roles")] public string[] Roles { get; set; } - //public int SessionTimeout { get; set; } - [DataMember(Name = "username")] public string Username { get; set; } diff --git a/src/Umbraco.Core/Services/ContentService.cs b/src/Umbraco.Core/Services/ContentService.cs index 439b18d9c6..e7298a5c6e 100644 --- a/src/Umbraco.Core/Services/ContentService.cs +++ b/src/Umbraco.Core/Services/ContentService.cs @@ -1227,6 +1227,13 @@ namespace Umbraco.Core.Services /// Optional Id of the user issueing the delete operation public void DeleteContentOfType(int contentTypeId, int userId = 0) { + //TODO: This currently this is called from the ContentTypeService but that needs to change, + // if we are deleting a content type, we should just delete the data and do this operation slightly differently. + // This method will recursively go lookup every content item, check if any of it's descendants are + // of a different type, move them to the recycle bin, then permanently delete the content items. + // The main problem with this is that for every content item being deleted, events are raised... + // which we need for many things like keeping caches in sync, but we can surely do this MUCH better. + using (new WriteLock(Locker)) { using (var uow = UowProvider.GetUnitOfWork()) diff --git a/src/Umbraco.Core/Services/ContentTypeService.cs b/src/Umbraco.Core/Services/ContentTypeService.cs index b30a66b376..5f337dc696 100644 --- a/src/Umbraco.Core/Services/ContentTypeService.cs +++ b/src/Umbraco.Core/Services/ContentTypeService.cs @@ -29,7 +29,7 @@ namespace Umbraco.Core.Services private readonly IContentService _contentService; private readonly IMediaService _mediaService; - //Support recursive locks because some of the methods that require locking call other methods that require locking. + //Support recursive locks because some of the methods that require locking call other methods that require locking. //for example, the Move method needs to be locked but this calls the Save method which also needs to be locked. private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); @@ -135,8 +135,8 @@ namespace Umbraco.Core.Services private Attempt SaveContainer( TypedEventHandler> savingEvent, TypedEventHandler> savedEvent, - EntityContainer container, - Guid containerObjectType, + EntityContainer container, + Guid containerObjectType, string objectTypeName, int userId) { var evtMsgs = EventMessagesFactory.Get(); @@ -164,7 +164,7 @@ namespace Umbraco.Core.Services using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType)) { repo.AddOrUpdate(container); - uow.Commit(); + uow.Commit(); } savedEvent.RaiseEvent(new SaveEventArgs(container, evtMsgs), this); @@ -253,14 +253,14 @@ namespace Umbraco.Core.Services .Where(x => x != int.MinValue && x != contentType.Id) .ToArray(); - return GetContentTypeContainers(ancestorIds); + return GetContentTypeContainers(ancestorIds); } public EntityContainer GetMediaTypeContainer(Guid containerId) { return GetContainer(containerId, Constants.ObjectTypes.MediaTypeGuid); } - + private EntityContainer GetContainer(Guid containerId, Guid containerObjectType) { var uow = UowProvider.GetUnitOfWork(); @@ -380,7 +380,7 @@ namespace Umbraco.Core.Services /// public IContentType Copy(IContentType original, string alias, string name, int parentId = -1) { - IContentType parent = null; + IContentType parent = null; if (parentId > 0) { parent = GetContentType(parentId); @@ -414,7 +414,7 @@ namespace Umbraco.Core.Services Mandate.ParameterNotNullOrEmpty(alias, "alias"); if (parent != null) { - Mandate.That(parent.HasIdentity, () => new InvalidOperationException("The parent content type must have an identity")); + Mandate.That(parent.HasIdentity, () => new InvalidOperationException("The parent content type must have an identity")); } var clone = original.DeepCloneWithResetIdentities(alias); @@ -440,7 +440,7 @@ namespace Umbraco.Core.Services //set to root clone.ParentId = -1; } - + Save(clone); return clone; } @@ -505,7 +505,7 @@ namespace Umbraco.Core.Services public IEnumerable GetAllContentTypes(IEnumerable ids) { using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork())) - { + { return repository.GetAll(ids.ToArray()); } } @@ -599,7 +599,7 @@ namespace Umbraco.Core.Services { //this should never occur, the content service should always be typed but we'll check anyways. _contentService.RePublishAll(); - } + } } else if (firstType is IMediaType) { @@ -608,10 +608,10 @@ namespace Umbraco.Core.Services if (typedContentService != null) { typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray()); - } + } } } - + } public int CountContentTypes() @@ -661,14 +661,17 @@ namespace Umbraco.Core.Services var contentType = compositionContentType as IContentType; var mediaType = compositionContentType as IMediaType; + var memberType = compositionContentType as IMemberType; // should NOT do it here but... v8! IContentTypeComposition[] allContentTypes; if (contentType != null) allContentTypes = GetAllContentTypes().Cast().ToArray(); else if (mediaType != null) allContentTypes = GetAllMediaTypes().Cast().ToArray(); + else if (memberType != null) + return; // no compositions on members, always validate else - throw new Exception("Composition is neither IContentType nor IMediaType?"); + throw new Exception("Composition is neither IContentType nor IMediaType nor IMemberType?"); var compositionAliases = compositionContentType.CompositionAliases(); var compositions = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y))); @@ -684,7 +687,7 @@ namespace Umbraco.Core.Services dependencies.Add(indirectReference); //Get all compositions for the current indirect reference var directReferences = indirectReference.ContentTypeComposition; - + foreach (var directReference in directReferences) { if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias)) continue; @@ -704,7 +707,7 @@ namespace Umbraco.Core.Services if (contentTypeDependency == null) continue; var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray(); if (intersect.Length == 0) continue; - + throw new InvalidCompositionException(compositionContentType.Alias, intersect.ToArray()); } } @@ -716,7 +719,7 @@ namespace Umbraco.Core.Services /// Optional id of the user saving the ContentType public void Save(IContentType contentType, int userId = 0) { - if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs(contentType), this)) + if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs(contentType), this)) return; using (new WriteLock(Locker)) @@ -746,7 +749,7 @@ namespace Umbraco.Core.Services { var asArray = contentTypes.ToArray(); - if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs(asArray), this)) + if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs(asArray), this)) return; using (new WriteLock(Locker)) @@ -782,12 +785,19 @@ namespace Umbraco.Core.Services /// Optional id of the user issueing the delete /// Deleting a will delete all the objects based on this public void Delete(IContentType contentType, int userId = 0) - { - if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs(contentType), this)) + { + if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs(contentType), this)) return; using (new WriteLock(Locker)) { + + //TODO: This needs to change, if we are deleting a content type, we should just delete the data, + // this method will recursively go lookup every content item, check if any of it's descendants are + // of a different type, move them to the recycle bin, then permanently delete the content items. + // The main problem with this is that for every content item being deleted, events are raised... + // which we need for many things like keeping caches in sync, but we can surely do this MUCH better. + _contentService.DeleteContentOfType(contentType.Id); var uow = UowProvider.GetUnitOfWork(); @@ -815,7 +825,7 @@ namespace Umbraco.Core.Services { var asArray = contentTypes.ToArray(); - if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs(asArray), this)) + if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs(asArray), this)) return; using (new WriteLock(Locker)) @@ -841,7 +851,7 @@ namespace Umbraco.Core.Services Audit(AuditType.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1); } } - + /// /// Gets an object by its Id /// @@ -974,7 +984,7 @@ namespace Umbraco.Core.Services public Attempt> MoveMediaType(IMediaType toMove, int containerId) { var evtMsgs = EventMessagesFactory.Get(); - + if (MovingMediaType.IsRaisedEventCancelled( new MoveEventArgs(evtMsgs, new MoveEventInfo(toMove, toMove.Path, containerId)), this)) @@ -1029,7 +1039,7 @@ namespace Umbraco.Core.Services var moveInfo = new List>(); var uow = UowProvider.GetUnitOfWork(); - using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid)) + using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid)) using (var repository = RepositoryFactory.CreateContentTypeRepository(uow)) { try @@ -1064,7 +1074,7 @@ namespace Umbraco.Core.Services /// Optional Id of the user saving the MediaType public void Save(IMediaType mediaType, int userId = 0) { - if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs(mediaType), this)) + if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs(mediaType), this)) return; using (new WriteLock(Locker)) @@ -1076,7 +1086,7 @@ namespace Umbraco.Core.Services mediaType.CreatorId = userId; repository.AddOrUpdate(mediaType); uow.Commit(); - + } UpdateContentXmlStructure(mediaType); @@ -1115,7 +1125,7 @@ namespace Umbraco.Core.Services } //save it all in one go - uow.Commit(); + uow.Commit(); } UpdateContentXmlStructure(asArray.Cast().ToArray()); @@ -1133,7 +1143,7 @@ namespace Umbraco.Core.Services /// Deleting a will delete all the objects based on this public void Delete(IMediaType mediaType, int userId = 0) { - if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs(mediaType), this)) + if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs(mediaType), this)) return; using (new WriteLock(Locker)) { @@ -1163,7 +1173,7 @@ namespace Umbraco.Core.Services { var asArray = mediaTypes.ToArray(); - if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs(asArray), this)) + if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs(asArray), this)) return; using (new WriteLock(Locker)) { @@ -1185,7 +1195,7 @@ namespace Umbraco.Core.Services } Audit(AuditType.Delete, string.Format("Delete MediaTypes performed by user"), userId, -1); - } + } } /// @@ -1274,7 +1284,7 @@ namespace Umbraco.Core.Services /// Occurs after Delete /// public static event TypedEventHandler> DeletedContentType; - + /// /// Occurs before Delete /// @@ -1284,7 +1294,7 @@ namespace Umbraco.Core.Services /// Occurs after Delete /// public static event TypedEventHandler> DeletedMediaType; - + /// /// Occurs before Save /// diff --git a/src/Umbraco.Core/Services/EntityXmlSerializer.cs b/src/Umbraco.Core/Services/EntityXmlSerializer.cs index 69c6708496..00bc7c5a9b 100644 --- a/src/Umbraco.Core/Services/EntityXmlSerializer.cs +++ b/src/Umbraco.Core/Services/EntityXmlSerializer.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Net.Http.Formatting; using System.Web; using System.Xml; using System.Xml.Linq; diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index b6d6d7ce27..5aae1dbd4a 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -41,6 +41,16 @@ namespace Umbraco.Core ToCSharpEscapeChars[escape[0]] = escape[1]; } + /// + /// Removes new lines and tabs + /// + /// + /// + 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 diff --git a/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs b/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs index a27b114f4d..87fc694fd1 100644 --- a/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs +++ b/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs @@ -60,7 +60,7 @@ namespace Umbraco.Core.Sync protected override bool RequiresDistributed(IEnumerable servers, ICacheRefresher refresher, MessageType dispatchType) { - // we don't care if there's servers listed or not, + // we don't care if there's servers listed or not, // if distributed call is enabled we will make the call return _initialized && DistributedEnabled; } @@ -139,12 +139,35 @@ namespace Umbraco.Core.Sync { if (_released) return; + var coldboot = false; if (_lastId < 0) // never synced before { - // we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new + // we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new // server and it will need to rebuild it's own caches, eg Lucene or the xml cache file. - _logger.Warn("No last synced Id found, this generally means this is a new server/install. The server will rebuild its caches and indexes and then adjust it's last synced id to the latest found in the database and will start maintaining cache updates based on that id"); + _logger.Warn("No last synced Id found, this generally means this is a new server/install." + + " The server will build its caches and indexes, and then adjust its last synced Id to the latest found in" + + " the database and maintain cache updates based on that Id."); + coldboot = true; + } + else + { + //check for how many instructions there are to process + var count = _appContext.DatabaseContext.Database.ExecuteScalar("SELECT COUNT(*) FROM umbracoCacheInstruction WHERE id > @lastId", new {lastId = _lastId}); + if (count > _options.MaxProcessingInstructionCount) + { + //too many instructions, proceed to cold boot + _logger.Warn("The instruction count ({0}) exceeds the specified MaxProcessingInstructionCount ({1})." + + " The server will skip existing instructions, rebuild its caches and indexes entirely, adjust its last synced Id" + + " to the latest found in the database and maintain cache updates based on that Id.", + () => count, () => _options.MaxProcessingInstructionCount); + + coldboot = true; + } + } + + if (coldboot) + { // go get the last id in the db and store it // note: do it BEFORE initializing otherwise some instructions might get lost // when doing it before, some instructions might run twice - not an issue @@ -169,7 +192,7 @@ namespace Umbraco.Core.Sync { lock (_locko) { - if (_syncing) + if (_syncing) return; if (_released) @@ -213,9 +236,9 @@ namespace Umbraco.Core.Sync private void ProcessDatabaseInstructions() { // NOTE - // we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that + // we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that // would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests - // (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are + // (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are // pending requests after being processed, they'll just be processed on the next poll. // // FIXME not true if we're running on a background thread, assuming we can? @@ -281,7 +304,7 @@ namespace Umbraco.Core.Sync /// Remove old instructions from the database /// /// - /// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause + /// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause /// the site to cold boot if there's been no instruction activity for more than DaysToRetainInstructions. /// See: http://issues.umbraco.org/issue/U4-7643#comment=67-25085 /// @@ -290,15 +313,15 @@ namespace Umbraco.Core.Sync var pruneDate = DateTime.UtcNow.AddDays(-_options.DaysToRetainInstructions); var sqlSyntax = _appContext.DatabaseContext.SqlSyntax; - //NOTE: this query could work on SQL server and MySQL: + //NOTE: this query could work on SQL server and MySQL: /* SELECT id FROM umbracoCacheInstruction - WHERE utcStamp < getdate() + WHERE utcStamp < getdate() AND id <> (SELECT MAX(id) FROM umbracoCacheInstruction) */ // However, this will not work on SQLCE and in fact it will be slower than the query we are - // using if the SQL server doesn't perform it's own query optimizations (i.e. since the above + // using if the SQL server doesn't perform it's own query optimizations (i.e. since the above // query could actually execute a sub query for every row found). So we've had to go with an // inner join which is faster and works on SQLCE but it's uglier to read. @@ -331,9 +354,9 @@ namespace Umbraco.Core.Sync var dtos = _appContext.DatabaseContext.Database.Fetch(sql); if (dtos.Count == 0) - _lastId = -1; + _lastId = -1; } - + /// /// Reads the last-synced id from file into memory. /// @@ -502,4 +525,3 @@ namespace Umbraco.Core.Sync #endregion } } - \ No newline at end of file diff --git a/src/Umbraco.Core/Sync/DatabaseServerMessengerOptions.cs b/src/Umbraco.Core/Sync/DatabaseServerMessengerOptions.cs index f1bebce10b..7559c37813 100644 --- a/src/Umbraco.Core/Sync/DatabaseServerMessengerOptions.cs +++ b/src/Umbraco.Core/Sync/DatabaseServerMessengerOptions.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; namespace Umbraco.Core.Sync -{ +{ /// /// Provides options to the . /// @@ -14,9 +14,15 @@ namespace Umbraco.Core.Sync public DatabaseServerMessengerOptions() { DaysToRetainInstructions = 2; // 2 days - ThrottleSeconds = 5; // 5 seconds + ThrottleSeconds = 5; // 5 second + MaxProcessingInstructionCount = 1000; } + /// + /// The maximum number of instructions that can be processed at startup; otherwise the server cold-boots (rebuilds its caches). + /// + public int MaxProcessingInstructionCount { get; set; } + /// /// A list of callbacks that will be invoked if the lastsynced.txt file does not exist. /// diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index cee2f8ee3f..4378b29586 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -112,18 +112,6 @@ - - ..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Extensions.dll - True - - - ..\packages\Microsoft.AspNet.WebApi.Client.4.0.30506.0\lib\net40\System.Net.Http.Formatting.dll - False - - - ..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Primitives.dll - True - @@ -175,6 +163,7 @@ + @@ -188,6 +177,7 @@ + @@ -484,7 +474,6 @@ - @@ -1414,7 +1403,9 @@ - + + Designer + @@ -1430,11 +1421,6 @@ - - - - - diff --git a/src/Umbraco.Web.UI.Client/src/views/components/umb-table.html b/src/Umbraco.Web.UI.Client/src/views/components/umb-table.html index b39ccf1da5..fdd7dd23c9 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/umb-table.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/umb-table.html @@ -8,9 +8,9 @@
+ ng-if="allowSelectAll" + ng-click="selectAll($event)" + ng-checked="isSelectedAll()">
@@ -22,8 +22,8 @@
+ ng-click="sort(column.alias, column.allowSorting)" + ng-class="{'sortable':column.allowSorting}" prevent-default> @@ -36,14 +36,13 @@
+ ng-click="selectItem(item, $index, $event)">
@@ -53,8 +52,8 @@ diff --git a/src/Umbraco.Web.UI.Client/src/views/datatypes/datatype.edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/datatypes/datatype.edit.controller.js index f2205a1d8e..d8f8557fa5 100644 --- a/src/Umbraco.Web.UI.Client/src/views/datatypes/datatype.edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/datatypes/datatype.edit.controller.js @@ -6,7 +6,7 @@ * @description * The controller for the content editor */ -function DataTypeEditController($scope, $routeParams, $location, appState, navigationService, treeService, dataTypeResource, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, formHelper, editorState, dataTypeHelper) { +function DataTypeEditController($scope, $routeParams, $location, appState, navigationService, treeService, dataTypeResource, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, formHelper, editorState, dataTypeHelper, eventsService) { //setup scope vars $scope.page = {}; @@ -15,6 +15,7 @@ function DataTypeEditController($scope, $routeParams, $location, appState, navig $scope.page.menu = {}; $scope.page.menu.currentSection = appState.getSectionState("currentSection"); $scope.page.menu.currentNode = null; + var evts = []; //method used to configure the pre-values when we retrieve them from the server function createPreValueProps(preVals) { @@ -68,6 +69,10 @@ function DataTypeEditController($scope, $routeParams, $location, appState, navig }); } else { + loadDataType(); + } + + function loadDataType() { $scope.page.loading = true; @@ -180,6 +185,17 @@ function DataTypeEditController($scope, $routeParams, $location, appState, navig }; + evts.push(eventsService.on("app.refreshEditor", function(name, error) { + loadDataType(); + })); + + //ensure to unregister from all events! + $scope.$on('$destroy', function () { + for (var e in evts) { + eventsService.unsubscribe(evts[e]); + } + }); + } angular.module("umbraco").controller("Umbraco.Editors.DataType.EditController", DataTypeEditController); diff --git a/src/Umbraco.Web.UI.Client/src/views/datatypes/move.controller.js b/src/Umbraco.Web.UI.Client/src/views/datatypes/move.controller.js index 580c08fd1a..15c173fe13 100644 --- a/src/Umbraco.Web.UI.Client/src/views/datatypes/move.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/datatypes/move.controller.js @@ -1,6 +1,6 @@ angular.module("umbraco") .controller("Umbraco.Editors.DataType.MoveController", - function ($scope, dataTypeResource, treeService, navigationService, notificationsService, appState) { + function ($scope, dataTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); @@ -45,6 +45,8 @@ angular.module("umbraco") } }); + eventsService.emit('app.refreshEditor'); + }, function (err) { $scope.success = false; $scope.error = err; diff --git a/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.controller.js index 3c8159bb8e..67d31c6d7f 100644 --- a/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.controller.js @@ -9,10 +9,11 @@ (function () { "use strict"; - function DocumentTypesEditController($scope, $routeParams, $injector, contentTypeResource, dataTypeResource, editorState, contentEditingHelper, formHelper, navigationService, iconHelper, contentTypeHelper, notificationsService, $filter, $q, localizationService, overlayHelper) { + function DocumentTypesEditController($scope, $routeParams, $injector, contentTypeResource, dataTypeResource, editorState, contentEditingHelper, formHelper, navigationService, iconHelper, contentTypeHelper, notificationsService, $filter, $q, localizationService, overlayHelper, eventsService) { var vm = this; var localizeSaving = localizationService.localize("general_saving"); + var evts = []; vm.save = save; @@ -158,6 +159,11 @@ }); } else { + loadDocumentType(); + } + + function loadDocumentType() { + vm.page.loading = true; contentTypeResource.getById($routeParams.id).then(function (dt) { @@ -168,6 +174,7 @@ vm.page.loading = false; }); + } @@ -317,6 +324,17 @@ }); } + evts.push(eventsService.on("app.refreshEditor", function(name, error) { + loadDocumentType(); + })); + + //ensure to unregister from all events! + $scope.$on('$destroy', function () { + for (var e in evts) { + eventsService.unsubscribe(evts[e]); + } + }); + } angular.module("umbraco").controller("Umbraco.Editors.DocumentTypes.EditController", DocumentTypesEditController); diff --git a/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.html b/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.html index c3c2a7f4ab..39efb9d1c6 100644 --- a/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/documenttypes/edit.html @@ -2,61 +2,63 @@ -
+ + name="vm.contentType.name" + alias="vm.contentType.alias" + description="vm.contentType.description" + navigation="vm.page.navigation" + icon="vm.contentType.icon"> - + - +
+ + +
- + - - + + - + - + - - - + + - - - - - + + + diff --git a/src/Umbraco.Web.UI.Client/src/views/documenttypes/move.controller.js b/src/Umbraco.Web.UI.Client/src/views/documenttypes/move.controller.js index 3cf3634371..e82385477a 100644 --- a/src/Umbraco.Web.UI.Client/src/views/documenttypes/move.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/documenttypes/move.controller.js @@ -1,6 +1,6 @@ angular.module("umbraco") .controller("Umbraco.Editors.DocumentTypes.MoveController", - function ($scope, contentTypeResource, treeService, navigationService, notificationsService, appState) { + function ($scope, contentTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); @@ -45,6 +45,8 @@ angular.module("umbraco") } }); + eventsService.emit('app.refreshEditor'); + }, function (err) { $scope.success = false; $scope.error = err; diff --git a/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.controller.js index 89e598ec27..8ece2cc9f1 100644 --- a/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.controller.js @@ -9,9 +9,11 @@ (function () { "use strict"; - function MediaTypesEditController($scope, $routeParams, mediaTypeResource, dataTypeResource, editorState, contentEditingHelper, formHelper, navigationService, iconHelper, contentTypeHelper, notificationsService, $filter, $q, localizationService, overlayHelper) { + function MediaTypesEditController($scope, $routeParams, mediaTypeResource, dataTypeResource, editorState, contentEditingHelper, formHelper, navigationService, iconHelper, contentTypeHelper, notificationsService, $filter, $q, localizationService, overlayHelper, eventsService) { + var vm = this; var localizeSaving = localizationService.localize("general_saving"); + var evts = []; vm.save = save; @@ -140,6 +142,10 @@ }); } else { + loadMediaType(); + } + + function loadMediaType() { vm.page.loading = true; mediaTypeResource.getById($routeParams.id).then(function(dt) { @@ -174,8 +180,39 @@ // type when server side validation fails - as opposed to content where we are capable of saving the content // item if server side validation fails redirectOnFailure: false, - //no-op for rebind callback... we don't really need to rebind for content types - rebindCallback: angular.noop + // we need to rebind... the IDs that have been created! + rebindCallback: function (origContentType, savedContentType) { + vm.contentType.id = savedContentType.id; + vm.contentType.groups.forEach(function (group) { + if (!group.name) return; + + var k = 0; + while (k < savedContentType.groups.length && savedContentType.groups[k].name != group.name) + k++; + if (k == savedContentType.groups.length) { + group.id = 0; + return; + } + + var savedGroup = savedContentType.groups[k]; + if (!group.id) group.id = savedGroup.id; + + group.properties.forEach(function (property) { + if (property.id || !property.alias) return; + + k = 0; + while (k < savedGroup.properties.length && savedGroup.properties[k].alias != property.alias) + k++; + if (k == savedGroup.properties.length) { + property.id = 0; + return; + } + + var savedProperty = savedGroup.properties[k]; + property.id = savedProperty.id; + }); + }); + } }).then(function (data) { //success syncTreeNode(vm.contentType, data.path); @@ -260,6 +297,17 @@ vm.currentNode = syncArgs.node; }); } + + evts.push(eventsService.on("app.refreshEditor", function(name, error) { + loadMediaType(); + })); + + //ensure to unregister from all events! + $scope.$on('$destroy', function () { + for (var e in evts) { + eventsService.unsubscribe(evts[e]); + } + }); } angular.module("umbraco").controller("Umbraco.Editors.MediaTypes.EditController", MediaTypesEditController); diff --git a/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.html b/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.html index b6c507ec0c..5bde09f8e0 100644 --- a/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/mediatypes/edit.html @@ -1,70 +1,69 @@
- + - + + name="vm.contentType.name" + alias="vm.contentType.alias" + description="vm.contentType.description" + navigation="vm.page.navigation" + icon="vm.contentType.icon">
- - - + +
- - + - - + + - + - + - - + + + + - - - - - +
-
diff --git a/src/Umbraco.Web.UI.Client/src/views/mediatypes/move.controller.js b/src/Umbraco.Web.UI.Client/src/views/mediatypes/move.controller.js index a8ce1e461a..f9bb584de7 100644 --- a/src/Umbraco.Web.UI.Client/src/views/mediatypes/move.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/mediatypes/move.controller.js @@ -1,6 +1,6 @@ angular.module("umbraco") .controller("Umbraco.Editors.MediaTypes.MoveController", - function ($scope, mediaTypeResource, treeService, navigationService, notificationsService, appState) { + function ($scope, mediaTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); @@ -46,6 +46,8 @@ angular.module("umbraco") } }); + eventsService.emit('app.refreshEditor'); + }, function (err) { $scope.success = false; $scope.error = err; diff --git a/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.controller.js index ed880da9b3..9c88f79015 100644 --- a/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.controller.js @@ -129,8 +129,39 @@ // type when server side validation fails - as opposed to content where we are capable of saving the content // item if server side validation fails redirectOnFailure: false, - //no-op for rebind callback... we don't really need to rebind for content types - rebindCallback: angular.noop + // we need to rebind... the IDs that have been created! + rebindCallback: function (origContentType, savedContentType) { + vm.contentType.id = savedContentType.id; + vm.contentType.groups.forEach(function (group) { + if (!group.name) return; + + var k = 0; + while (k < savedContentType.groups.length && savedContentType.groups[k].name != group.name) + k++; + if (k == savedContentType.groups.length) { + group.id = 0; + return; + } + + var savedGroup = savedContentType.groups[k]; + if (!group.id) group.id = savedGroup.id; + + group.properties.forEach(function (property) { + if (property.id || !property.alias) return; + + k = 0; + while (k < savedGroup.properties.length && savedGroup.properties[k].alias != property.alias) + k++; + if (k == savedGroup.properties.length) { + property.id = 0; + return; + } + + var savedProperty = savedGroup.properties[k]; + property.id = savedProperty.id; + }); + }); + } }).then(function (data) { //success syncTreeNode(vm.contentType, data.path); diff --git a/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.html b/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.html index 64ffe504b1..eb34aae6cc 100644 --- a/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/membertypes/edit.html @@ -1,67 +1,69 @@
- + + +
- - + name="vm.contentType.name" + alias="vm.contentType.alias" + description="vm.contentType.description" + navigation="vm.page.navigation" + icon="vm.contentType.icon">
- + +
- - + - - + + - + - + - - + + + + - - - - +
-
diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/changepassword/changepassword.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/changepassword/changepassword.html index c6c9bb115f..78ae6afa6b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/changepassword/changepassword.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/changepassword/changepassword.html @@ -5,12 +5,14 @@ {{model.value.generatedPassword}}
-
- Change password +
- + - + - + - + + autocomplete="off"/> - Passwords must match - + + The confirmed password doesn't match the new password! + + - Cancel + + Cancel +
diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html index dd35757397..a54fdda966 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html @@ -9,7 +9,7 @@
diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/bulkActionPermissions.prevalues.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/bulkActionPermissions.prevalues.html new file mode 100644 index 0000000000..8a5ca613e2 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/bulkActionPermissions.prevalues.html @@ -0,0 +1,32 @@ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/layouts/list/list.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/layouts/list/list.html index 276274dce3..96bebb7abf 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/layouts/list/list.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/layouts/list/list.html @@ -22,6 +22,7 @@ - + - + - - - - - - - - - - - {{ selectedItemsCount() }} of {{ listViewResultSet.items.length }} selected - - -
-
-
-
- -
- - - - - - - - - - - - -