From 08ce8bc4dcb6d278b512236635ac7e01625868cf Mon Sep 17 00:00:00 2001 From: Stephan Date: Tue, 20 Jun 2017 12:12:29 +0200 Subject: [PATCH] Remove legacy projects --- src/SQLCE4Umbraco/Properties/AssemblyInfo.cs | 21 - src/SQLCE4Umbraco/SqlCE4Umbraco.csproj | 58 - .../SqlCE4Umbraco.csproj.DotSettings | 2 - src/SQLCE4Umbraco/SqlCEDataReader.cs | 44 - src/SQLCE4Umbraco/SqlCEHelper.cs | 253 --- src/SQLCE4Umbraco/SqlCEInstaller.cs | 141 -- src/SQLCE4Umbraco/SqlCEParameter.cs | 34 - src/SQLCE4Umbraco/SqlCETableUtility.cs | 250 -- src/SQLCE4Umbraco/SqlCEUtility.cs | 56 - src/SQLCE4Umbraco/SqlCeApplicationBlock.cs | 270 --- src/SQLCE4Umbraco/SqlCeContextGuardian.cs | 64 - src/SQLCE4Umbraco/SqlCeProviderException.cs | 20 - .../PublishedContentCacheTests.cs | 2 - .../PublishedMediaCacheTests.cs | 41 +- src/Umbraco.Tests/Issues/U9560.cs | 22 +- src/Umbraco.Tests/Macros/MacroTests.cs | 10 - .../Upgrades/SqlCeDataUpgradeTest.cs | 3 +- .../Migrations/Upgrades/SqlCeUpgradeTest.cs | 10 +- .../Upgrades/ValidateOlderSchemaTest.cs | 4 +- .../Plugins/PluginManagerTests.cs | 11 +- src/Umbraco.Tests/Plugins/TypeFinderTests.cs | 12 +- .../PublishedContent/PublishedMediaTests.cs | 110 +- .../Templates/MasterPageHelperTests.cs | 8 +- src/Umbraco.Tests/TestHelpers/TestHelper.cs | 27 +- .../TestHelpers/TestWithDatabaseBase.cs | 3 +- .../TreesAndSections/SectionTests.cs | 1 - src/Umbraco.Tests/UI/LegacyDialogTests.cs | 5 - src/Umbraco.Tests/Umbraco.Tests.csproj | 16 - src/umbraco.cms/Properties/AssemblyInfo.cs | 17 - src/umbraco.cms/businesslogic/CMSNode.cs | 1082 --------- .../businesslogic/CMSPreviewNode.cs | 41 - src/umbraco.cms/businesslogic/Content.cs | 365 --- src/umbraco.cms/businesslogic/ContentType.cs | 1686 -------------- .../businesslogic/LegacySqlHelper.cs | 54 - .../FileResources/PackageFiles.Designer.cs | 73 - .../Packager/FileResources/PackageFiles.resx | 124 - .../Packager/FileResources/Packages.config | 2 - .../businesslogic/Packager/Installer.cs | 803 ------- .../businesslogic/Packager/Package.cs | 143 -- .../PackageInstance/CreatedPackage.cs | 376 ---- .../PackageInstance/IPackageInstance.cs | 28 - .../PackageInstance/InstalledPackage.cs | 199 -- .../PackageInstance/PackageActions.cs | 71 - .../PackageInstance/PackageInstance.cs | 103 - .../PackageInstance/PackagerUtility.cs | 344 --- .../Packager/Repositories/Repository.cs | 291 --- .../Repositories/RepositoryWebservice.cs | 2002 ----------------- .../Packager/RequirementsType.cs | 8 - .../businesslogic/Packager/Settings.cs | 83 - .../businesslogic/Packager/data.cs | 415 ---- src/umbraco.cms/businesslogic/Permission.cs | 176 -- .../businesslogic/language/Item.cs | 160 -- .../businesslogic/language/Language.cs | 274 --- src/umbraco.cms/businesslogic/macro/Macro.cs | 426 ---- .../businesslogic/macro/MacroProperty.cs | 240 -- src/umbraco.cms/businesslogic/media/Media.cs | 347 --- .../businesslogic/media/MediaFactory.cs | 40 - .../businesslogic/media/MediaType.cs | 166 -- .../businesslogic/member/Member.cs | 1101 --------- .../businesslogic/member/MemberType.cs | 193 -- .../propertytype/PropertyTypeGroup.cs | 163 -- .../propertytype/propertytype.cs | 444 ---- src/umbraco.cms/businesslogic/task/Task.cs | 268 --- .../businesslogic/task/TaskType.cs | 123 - src/umbraco.cms/businesslogic/task/Tasks.cs | 35 - .../businesslogic/template/Template.cs | 497 ---- src/umbraco.cms/businesslogic/web/Document.cs | 644 ------ .../businesslogic/web/DocumentType.cs | 458 ---- .../businesslogic/web/DocumentVersionList.cs | 63 - src/umbraco.cms/businesslogic/web/Domain.cs | 171 -- .../businesslogic/web/StyleSheet.cs | 248 -- .../businesslogic/web/StylesheetProperty.cs | 121 - src/umbraco.cms/umbraco.cms.csproj | 77 - .../umbraco.cms.csproj.DotSettings | 2 - src/umbraco.controls/CodeArea.cs | 243 -- src/umbraco.controls/DataAttributes.cs | 20 - src/umbraco.controls/FieldDropDownList.cs | 72 - src/umbraco.controls/MenuButton.cs | 73 - src/umbraco.controls/MenuButtonI.cs | 60 - src/umbraco.controls/MenuIcon.cs | 69 - src/umbraco.controls/MenuIconClass.cs | 39 - src/umbraco.controls/MenuIconI.cs | 28 - src/umbraco.controls/MenuSplitButton.cs | 65 - src/umbraco.controls/Panel.cs | 123 - src/umbraco.controls/ProgressBar.cs | 24 - .../Properties/AssemblyInfo.cs | 22 - src/umbraco.controls/PropertyGroup.cs | 56 - src/umbraco.controls/PropertyPanel.cs | 73 - src/umbraco.controls/ScrollingMenu.cs | 154 -- src/umbraco.controls/Splitter.cs | 15 - src/umbraco.controls/TabPage.cs | 99 - src/umbraco.controls/TabView.cs | 144 -- .../TreePicker/BaseTreePicker.cs | 276 --- .../TreePicker/BaseTreePicker.js | 31 - .../BaseTreePickerScripts.Designer.cs | 83 - .../TreePicker/BaseTreePickerScripts.resx | 124 - .../TreePicker/SimpleContentPicker.cs | 30 - .../TreePicker/SimpleMediaPicker.cs | 29 - src/umbraco.controls/feedback.cs | 55 - src/umbraco.controls/pane.cs | 117 - src/umbraco.controls/umbraco.controls.csproj | 68 - .../umbraco.controls.csproj.DotSettings | 2 - src/umbraco.datalayer/DataLayerHelper.cs | 174 -- .../Extensions/ISqlHelperExtension.cs | 51 - src/umbraco.datalayer/Extensions/Logger.cs | 139 -- .../Extensions/SqlHelperExtender.cs | 217 -- .../Extensions/SqlHelperExtension.cs | 59 - src/umbraco.datalayer/IParameter.cs | 31 - src/umbraco.datalayer/IParameterContainer.cs | 25 - src/umbraco.datalayer/IRecordsReader.cs | 169 -- src/umbraco.datalayer/ISqlHelper.cs | 96 - .../Properties/AssemblyInfo.cs | 29 - src/umbraco.datalayer/RecordsReaderAdapter.cs | 444 ---- src/umbraco.datalayer/SqlHelper.cs | 478 ---- src/umbraco.datalayer/SqlHelperException.cs | 102 - .../SqlServer/SqlServerDataReader.cs | 43 - .../SqlHelpers/SqlServer/SqlServerHelper.cs | 111 - .../SqlServer/SqlServerInstaller.cs | 100 - .../SqlServer/SqlServerParameter.cs | 33 - .../SqlServer/SqlServerTableUtility.cs | 248 -- .../SqlHelpers/SqlServer/SqlServerUtility.cs | 56 - src/umbraco.datalayer/SqlParameterAdapter.cs | 70 - src/umbraco.datalayer/SqlParser.cs | 254 --- src/umbraco.datalayer/StringExtensions.cs | 22 - src/umbraco.datalayer/UmbracoException.cs | 109 - src/umbraco.datalayer/Utility/BaseUtility.cs | 53 - .../Utility/DefaultUtilitySet.cs | 78 - src/umbraco.datalayer/Utility/IUtilitySet.cs | 36 - .../Utility/Installer/DatabaseVersion.cs | 32 - .../Installer/DefaultInstallerUtility.cs | 265 --- .../Utility/Installer/IInstallerUtility.cs | 87 - .../Utility/Installer/VersionSpecs.cs | 47 - .../Utility/Table/DefaultField.cs | 88 - .../Utility/Table/DefaultTable.cs | 195 -- .../Utility/Table/DefaultTableUtility.cs | 78 - .../Utility/Table/FieldProperties.cs | 29 - src/umbraco.datalayer/Utility/Table/IField.cs | 42 - src/umbraco.datalayer/Utility/Table/ITable.cs | 81 - .../Utility/Table/ITableUtility.cs | 46 - .../umbraco.datalayer.csproj | 61 - .../umbraco.datalayer.csproj.DotSettings | 2 - src/umbraco.sln | 28 +- 142 files changed, 116 insertions(+), 22631 deletions(-) delete mode 100644 src/SQLCE4Umbraco/Properties/AssemblyInfo.cs delete mode 100644 src/SQLCE4Umbraco/SqlCE4Umbraco.csproj delete mode 100644 src/SQLCE4Umbraco/SqlCE4Umbraco.csproj.DotSettings delete mode 100644 src/SQLCE4Umbraco/SqlCEDataReader.cs delete mode 100644 src/SQLCE4Umbraco/SqlCEHelper.cs delete mode 100644 src/SQLCE4Umbraco/SqlCEInstaller.cs delete mode 100644 src/SQLCE4Umbraco/SqlCEParameter.cs delete mode 100644 src/SQLCE4Umbraco/SqlCETableUtility.cs delete mode 100644 src/SQLCE4Umbraco/SqlCEUtility.cs delete mode 100644 src/SQLCE4Umbraco/SqlCeApplicationBlock.cs delete mode 100644 src/SQLCE4Umbraco/SqlCeContextGuardian.cs delete mode 100644 src/SQLCE4Umbraco/SqlCeProviderException.cs delete mode 100644 src/umbraco.cms/Properties/AssemblyInfo.cs delete mode 100644 src/umbraco.cms/businesslogic/CMSNode.cs delete mode 100644 src/umbraco.cms/businesslogic/CMSPreviewNode.cs delete mode 100644 src/umbraco.cms/businesslogic/Content.cs delete mode 100644 src/umbraco.cms/businesslogic/ContentType.cs delete mode 100644 src/umbraco.cms/businesslogic/LegacySqlHelper.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.Designer.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.resx delete mode 100644 src/umbraco.cms/businesslogic/Packager/FileResources/Packages.config delete mode 100644 src/umbraco.cms/businesslogic/Packager/Installer.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/Package.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/PackageInstance/CreatedPackage.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/PackageInstance/IPackageInstance.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageInstance.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/PackageInstance/PackagerUtility.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/RequirementsType.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/Settings.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/data.cs delete mode 100644 src/umbraco.cms/businesslogic/Permission.cs delete mode 100644 src/umbraco.cms/businesslogic/language/Item.cs delete mode 100644 src/umbraco.cms/businesslogic/language/Language.cs delete mode 100644 src/umbraco.cms/businesslogic/macro/Macro.cs delete mode 100644 src/umbraco.cms/businesslogic/macro/MacroProperty.cs delete mode 100644 src/umbraco.cms/businesslogic/media/Media.cs delete mode 100644 src/umbraco.cms/businesslogic/media/MediaFactory.cs delete mode 100644 src/umbraco.cms/businesslogic/media/MediaType.cs delete mode 100644 src/umbraco.cms/businesslogic/member/Member.cs delete mode 100644 src/umbraco.cms/businesslogic/member/MemberType.cs delete mode 100644 src/umbraco.cms/businesslogic/propertytype/PropertyTypeGroup.cs delete mode 100644 src/umbraco.cms/businesslogic/propertytype/propertytype.cs delete mode 100644 src/umbraco.cms/businesslogic/task/Task.cs delete mode 100644 src/umbraco.cms/businesslogic/task/TaskType.cs delete mode 100644 src/umbraco.cms/businesslogic/task/Tasks.cs delete mode 100644 src/umbraco.cms/businesslogic/template/Template.cs delete mode 100644 src/umbraco.cms/businesslogic/web/Document.cs delete mode 100644 src/umbraco.cms/businesslogic/web/DocumentType.cs delete mode 100644 src/umbraco.cms/businesslogic/web/DocumentVersionList.cs delete mode 100644 src/umbraco.cms/businesslogic/web/Domain.cs delete mode 100644 src/umbraco.cms/businesslogic/web/StyleSheet.cs delete mode 100644 src/umbraco.cms/businesslogic/web/StylesheetProperty.cs delete mode 100644 src/umbraco.cms/umbraco.cms.csproj delete mode 100644 src/umbraco.cms/umbraco.cms.csproj.DotSettings delete mode 100644 src/umbraco.controls/CodeArea.cs delete mode 100644 src/umbraco.controls/DataAttributes.cs delete mode 100644 src/umbraco.controls/FieldDropDownList.cs delete mode 100644 src/umbraco.controls/MenuButton.cs delete mode 100644 src/umbraco.controls/MenuButtonI.cs delete mode 100644 src/umbraco.controls/MenuIcon.cs delete mode 100644 src/umbraco.controls/MenuIconClass.cs delete mode 100644 src/umbraco.controls/MenuIconI.cs delete mode 100644 src/umbraco.controls/MenuSplitButton.cs delete mode 100644 src/umbraco.controls/Panel.cs delete mode 100644 src/umbraco.controls/ProgressBar.cs delete mode 100644 src/umbraco.controls/Properties/AssemblyInfo.cs delete mode 100644 src/umbraco.controls/PropertyGroup.cs delete mode 100644 src/umbraco.controls/PropertyPanel.cs delete mode 100644 src/umbraco.controls/ScrollingMenu.cs delete mode 100644 src/umbraco.controls/Splitter.cs delete mode 100644 src/umbraco.controls/TabPage.cs delete mode 100644 src/umbraco.controls/TabView.cs delete mode 100644 src/umbraco.controls/TreePicker/BaseTreePicker.cs delete mode 100644 src/umbraco.controls/TreePicker/BaseTreePicker.js delete mode 100644 src/umbraco.controls/TreePicker/BaseTreePickerScripts.Designer.cs delete mode 100644 src/umbraco.controls/TreePicker/BaseTreePickerScripts.resx delete mode 100644 src/umbraco.controls/TreePicker/SimpleContentPicker.cs delete mode 100644 src/umbraco.controls/TreePicker/SimpleMediaPicker.cs delete mode 100644 src/umbraco.controls/feedback.cs delete mode 100644 src/umbraco.controls/pane.cs delete mode 100644 src/umbraco.controls/umbraco.controls.csproj delete mode 100644 src/umbraco.controls/umbraco.controls.csproj.DotSettings delete mode 100644 src/umbraco.datalayer/DataLayerHelper.cs delete mode 100644 src/umbraco.datalayer/Extensions/ISqlHelperExtension.cs delete mode 100644 src/umbraco.datalayer/Extensions/Logger.cs delete mode 100644 src/umbraco.datalayer/Extensions/SqlHelperExtender.cs delete mode 100644 src/umbraco.datalayer/Extensions/SqlHelperExtension.cs delete mode 100644 src/umbraco.datalayer/IParameter.cs delete mode 100644 src/umbraco.datalayer/IParameterContainer.cs delete mode 100644 src/umbraco.datalayer/IRecordsReader.cs delete mode 100644 src/umbraco.datalayer/ISqlHelper.cs delete mode 100644 src/umbraco.datalayer/Properties/AssemblyInfo.cs delete mode 100644 src/umbraco.datalayer/RecordsReaderAdapter.cs delete mode 100644 src/umbraco.datalayer/SqlHelper.cs delete mode 100644 src/umbraco.datalayer/SqlHelperException.cs delete mode 100644 src/umbraco.datalayer/SqlHelpers/SqlServer/SqlServerDataReader.cs delete mode 100644 src/umbraco.datalayer/SqlHelpers/SqlServer/SqlServerHelper.cs delete mode 100644 src/umbraco.datalayer/SqlHelpers/SqlServer/SqlServerInstaller.cs delete mode 100644 src/umbraco.datalayer/SqlHelpers/SqlServer/SqlServerParameter.cs delete mode 100644 src/umbraco.datalayer/SqlHelpers/SqlServer/SqlServerTableUtility.cs delete mode 100644 src/umbraco.datalayer/SqlHelpers/SqlServer/SqlServerUtility.cs delete mode 100644 src/umbraco.datalayer/SqlParameterAdapter.cs delete mode 100644 src/umbraco.datalayer/SqlParser.cs delete mode 100644 src/umbraco.datalayer/StringExtensions.cs delete mode 100644 src/umbraco.datalayer/UmbracoException.cs delete mode 100644 src/umbraco.datalayer/Utility/BaseUtility.cs delete mode 100644 src/umbraco.datalayer/Utility/DefaultUtilitySet.cs delete mode 100644 src/umbraco.datalayer/Utility/IUtilitySet.cs delete mode 100644 src/umbraco.datalayer/Utility/Installer/DatabaseVersion.cs delete mode 100644 src/umbraco.datalayer/Utility/Installer/DefaultInstallerUtility.cs delete mode 100644 src/umbraco.datalayer/Utility/Installer/IInstallerUtility.cs delete mode 100644 src/umbraco.datalayer/Utility/Installer/VersionSpecs.cs delete mode 100644 src/umbraco.datalayer/Utility/Table/DefaultField.cs delete mode 100644 src/umbraco.datalayer/Utility/Table/DefaultTable.cs delete mode 100644 src/umbraco.datalayer/Utility/Table/DefaultTableUtility.cs delete mode 100644 src/umbraco.datalayer/Utility/Table/FieldProperties.cs delete mode 100644 src/umbraco.datalayer/Utility/Table/IField.cs delete mode 100644 src/umbraco.datalayer/Utility/Table/ITable.cs delete mode 100644 src/umbraco.datalayer/Utility/Table/ITableUtility.cs delete mode 100644 src/umbraco.datalayer/umbraco.datalayer.csproj delete mode 100644 src/umbraco.datalayer/umbraco.datalayer.csproj.DotSettings diff --git a/src/SQLCE4Umbraco/Properties/AssemblyInfo.cs b/src/SQLCE4Umbraco/Properties/AssemblyInfo.cs deleted file mode 100644 index cd12cfbb0a..0000000000 --- a/src/SQLCE4Umbraco/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SqlCE4Umbraco")] -[assembly: AssemblyDescription("Umbraco specific Sql Ce Provider")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("Umbraco CMS")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("04436b0a-1dc6-4ee1-9d96-4c04f1a9f429")] - -[assembly: InternalsVisibleTo("Umbraco.Tests")] \ No newline at end of file diff --git a/src/SQLCE4Umbraco/SqlCE4Umbraco.csproj b/src/SQLCE4Umbraco/SqlCE4Umbraco.csproj deleted file mode 100644 index 006e387126..0000000000 --- a/src/SQLCE4Umbraco/SqlCE4Umbraco.csproj +++ /dev/null @@ -1,58 +0,0 @@ - - - - v4.6.1 - false - {5BA5425F-27A7-4677-865E-82246498AA2E} - Library - SQLCE4Umbraco - SQLCE4Umbraco - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - bin\Release\SQLCE4Umbraco.XML - false - - - - - - - - - - - - - - - - - umbraco.datalayer - - - - - - Properties\SolutionInfo.cs - - - - \ No newline at end of file diff --git a/src/SQLCE4Umbraco/SqlCE4Umbraco.csproj.DotSettings b/src/SQLCE4Umbraco/SqlCE4Umbraco.csproj.DotSettings deleted file mode 100644 index c54c126d26..0000000000 --- a/src/SQLCE4Umbraco/SqlCE4Umbraco.csproj.DotSettings +++ /dev/null @@ -1,2 +0,0 @@ - - CSharp70 \ No newline at end of file diff --git a/src/SQLCE4Umbraco/SqlCEDataReader.cs b/src/SQLCE4Umbraco/SqlCEDataReader.cs deleted file mode 100644 index 88734237a3..0000000000 --- a/src/SQLCE4Umbraco/SqlCEDataReader.cs +++ /dev/null @@ -1,44 +0,0 @@ -/************************************************************************************ - * - * Umbraco Data Layer - * MIT Licensed work - * ©2008 Ruben Verborgh - * - ***********************************************************************************/ - -using System.Data.SqlServerCe; -using umbraco.DataLayer; - -namespace SqlCE4Umbraco -{ - /// - /// Class that adapts a SqlDataReader.SqlDataReader to a RecordsReaderAdapter. - /// - public class SqlCeDataReaderHelper : RecordsReaderAdapter - { - #region Public Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The data reader. - public SqlCeDataReaderHelper(System.Data.SqlServerCe.SqlCeDataReader dataReader) : base(dataReader) { } - - #endregion - - #region RecordsReaderAdapter Members - - /// - /// Gets a value indicating whether this instance has records. - /// - /// - /// true if this instance has records; otherwise, false. - /// - public override bool HasRecords - { - get { return DataReader.HasRows; } - } - - #endregion - } -} diff --git a/src/SQLCE4Umbraco/SqlCEHelper.cs b/src/SQLCE4Umbraco/SqlCEHelper.cs deleted file mode 100644 index a8567abd67..0000000000 --- a/src/SQLCE4Umbraco/SqlCEHelper.cs +++ /dev/null @@ -1,253 +0,0 @@ -/************************************************************************************ - * - * Umbraco Data Layer - * MIT Licensed work - * ©2008 Ruben Verborgh - * - ***********************************************************************************/ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlServerCe; -using System.Linq; -using System.Xml; -using System.Diagnostics; -using umbraco.DataLayer; -using umbraco.DataLayer.SqlHelpers.SqlServer; - -namespace SqlCE4Umbraco -{ - /// - /// Sql Helper for an SQL Server database. - /// - public class SqlCEHelper : SqlHelper - { - /// - /// Initializes a new instance of the class. - /// - /// The connection string. - public SqlCEHelper(string connectionString) : base(connectionString) - { - m_Utility = new SqlCEUtility(this); - } - - /// - /// Checks if the actual database exists, if it doesn't then it will create it - /// - internal void CreateEmptyDatabase() - { - var localConnection = new SqlCeConnection(ConnectionString); - if (!System.IO.File.Exists(ReplaceDataDirectory(localConnection.Database))) - { - using (var sqlCeEngine = new SqlCeEngine(ConnectionString)) - { - sqlCeEngine.CreateDatabase(); - } - } - } - - /// - /// Most likely only will be used for unit tests but will remove all tables from the database - /// - internal void ClearDatabase() - { - // drop constraints before tables to avoid exceptions - // looping on try/catching exceptions was not really nice - - // http://stackoverflow.com/questions/536350/drop-all-the-tables-stored-procedures-triggers-constriants-and-all-the-depend - - var localConnection = new SqlCeConnection(ConnectionString); - if (System.IO.File.Exists(ReplaceDataDirectory(localConnection.Database))) - { - List tables; - - // drop foreign keys - // SQL may need "where constraint_catalog=DB_NAME() and ..." - tables = new List(); - using (var reader = ExecuteReader("select table_name from information_schema.table_constraints where constraint_type = 'FOREIGN KEY' order by table_name")) - { - while (reader.Read()) tables.Add(reader.GetString("table_name").Trim()); - } - - foreach (var table in tables) - { - var constraints = new List(); - using (var reader = ExecuteReader("select constraint_name from information_schema.table_constraints where constraint_type = 'FOREIGN KEY' and table_name = '" + table + "' order by constraint_name")) - { - while (reader.Read()) constraints.Add(reader.GetString("constraint_name").Trim()); - } - foreach (var constraint in constraints) - { - // SQL may need "[dbo].[table]" - ExecuteNonQuery("alter table [" + table + "] drop constraint [" + constraint + "]"); - } - } - - // drop primary keys - // SQL may need "where constraint_catalog=DB_NAME() and ..." - tables = new List(); - using (var reader = ExecuteReader("select table_name from information_schema.table_constraints where constraint_type = 'PRIMARY KEY' order by table_name")) - { - while (reader.Read()) tables.Add(reader.GetString("table_name").Trim()); - } - - foreach (var table in tables) - { - var constraints = new List(); - using (var reader = ExecuteReader("select constraint_name from information_schema.table_constraints where constraint_type = 'PRIMARY KEY' and table_name = '" + table + "' order by constraint_name")) - { - while (reader.Read()) constraints.Add(reader.GetString("constraint_name").Trim()); - } - foreach (var constraint in constraints) - { - // SQL may need "[dbo].[table]" - ExecuteNonQuery("alter table [" + table + "] drop constraint [" + constraint + "]"); - } - } - - // drop tables - tables = new List(); - using (var reader = ExecuteReader("select table_name from information_schema.tables where table_type <> 'VIEW' order by table_name")) - { - while (reader.Read()) tables.Add(reader.GetString("table_name").Trim()); - } - - foreach (var table in tables) - { - ExecuteNonQuery("drop table [" + table + "]"); - } - } - } - - /// - /// Drops all foreign keys on a table. - /// - /// The name of the table. - /// To be used in unit tests. - internal void DropForeignKeys(string table) - { - var constraints = new List(); - using (var reader = ExecuteReader("select constraint_name from information_schema.table_constraints where constraint_type = 'FOREIGN KEY' and table_name = '" + table + "' order by constraint_name")) - { - while (reader.Read()) constraints.Add(reader.GetString("constraint_name").Trim()); - } - foreach (var constraint in constraints) - { - // SQL may need "[dbo].[table]" - ExecuteNonQuery("alter table [" + table + "] drop constraint [" + constraint + "]"); - } - } - - /// - /// Replaces the data directory with a local path. - /// - /// The path. - /// A local path with the resolved 'DataDirectory' mapping. - private string ReplaceDataDirectory(string path) - { - if (!string.IsNullOrWhiteSpace(path) && path.Contains("|DataDirectory|")) - { - var dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string; - if (!string.IsNullOrEmpty(dataDirectory)) - { - path = path.Contains(@"|\") - ? path.Replace("|DataDirectory|", dataDirectory) - : path.Replace("|DataDirectory|", dataDirectory + System.IO.Path.DirectorySeparatorChar); - } - } - - return path; - } - - /// - /// Creates a new parameter for use with this specific implementation of ISqlHelper. - /// - /// Name of the parameter. - /// Value of the parameter. - /// A new parameter of the correct type. - /// Abstract factory pattern - public override IParameter CreateParameter(string parameterName, object value) - { - return new SqlCEParameter(parameterName, value); - } - - /// - /// Executes a command that returns a single value. - /// - /// The command text. - /// The parameters. - /// The return value of the command. - protected override object ExecuteScalar(string commandText, SqlCeParameter[] parameters) - { -#if DEBUG && DebugDataLayer - // Log Query Execution - Trace.TraceInformation(GetType().Name + " SQL ExecuteScalar: " + commandText); -#endif - using (var cc = UseCurrentConnection) - { - return SqlCeApplicationBlock.ExecuteScalar( - (SqlCeConnection) cc.Connection, (SqlCeTransaction) cc.Transaction, - CommandType.Text, commandText, parameters); - } - } - - /// - /// Executes a command and returns the number of rows affected. - /// - /// The command text. - /// The parameters. - /// - /// The number of rows affected by the command. - /// - protected override int ExecuteNonQuery(string commandText, SqlCeParameter[] parameters) - { -#if DEBUG && DebugDataLayer - // Log Query Execution - Trace.TraceInformation(GetType().Name + " SQL ExecuteNonQuery: " + commandText); -#endif - - using (var cc = UseCurrentConnection) - { - return SqlCeApplicationBlock.ExecuteNonQuery( - (SqlCeConnection) cc.Connection, (SqlCeTransaction) cc.Transaction, - CommandType.Text, commandText, parameters); - } - } - - /// - /// Executes a command and returns a records reader containing the results. - /// - /// The command text. - /// The parameters. - /// - /// A data reader containing the results of the command. - /// - protected override IRecordsReader ExecuteReader(string commandText, SqlCeParameter[] parameters) - { -#if DEBUG && DebugDataLayer - // Log Query Execution - Trace.TraceInformation(GetType().Name + " SQL ExecuteReader: " + commandText); -#endif - - using (var cc = UseCurrentConnection) - { - return new SqlCeDataReaderHelper(SqlCeApplicationBlock.ExecuteReader( - (SqlCeConnection) cc.Connection, (SqlCeTransaction) cc.Transaction, - CommandType.Text, commandText, parameters)); - } - } - - - internal IRecordsReader ExecuteReader(string commandText) - { - return ExecuteReader(commandText, new SqlCEParameter(string.Empty, string.Empty)); - } - - - internal int ExecuteNonQuery(string commandText) - { - return ExecuteNonQuery(commandText, new SqlCEParameter(string.Empty, string.Empty)); - } - } -} \ No newline at end of file diff --git a/src/SQLCE4Umbraco/SqlCEInstaller.cs b/src/SQLCE4Umbraco/SqlCEInstaller.cs deleted file mode 100644 index 80a669e59c..0000000000 --- a/src/SQLCE4Umbraco/SqlCEInstaller.cs +++ /dev/null @@ -1,141 +0,0 @@ -/************************************************************************************ - * - * Umbraco Data Layer - * MIT Licensed work - * ©2008 Ruben Verborgh - * - ***********************************************************************************/ - -using System; -using System.Resources; -using SQLCE4Umbraco; -using umbraco.DataLayer.Utility.Installer; -using System.Diagnostics; - -namespace SqlCE4Umbraco -{ - /// - /// Database installer for an SQL Server data source. - /// - [Obsolete("The legacy installers are no longer used and will be removed from the codebase in the future")] - public class SqlCEInstaller : DefaultInstallerUtility - { - #region Private Constants - - /// The latest database version this installer supports. - private const DatabaseVersion LatestVersionSupported = DatabaseVersion.Version4_8; - - /// The specifications to determine the database version. - private static readonly VersionSpecs[] m_VersionSpecs = new VersionSpecs[] { - new VersionSpecs("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS LEFT OUTER JOIN umbracoApp ON appAlias = appAlias WHERE CONSTRAINT_NAME = 'FK_umbracoUser2app_umbracoApp'", 0, DatabaseVersion.Version4_8), - new VersionSpecs("SELECT id FROM umbracoNode WHERE id = -21", 1, DatabaseVersion.Version4_1), - new VersionSpecs("SELECT action FROM umbracoAppTree",DatabaseVersion.Version4), - new VersionSpecs("SELECT description FROM cmsContentType",DatabaseVersion.Version3), - new VersionSpecs("SELECT id FROM sysobjects",DatabaseVersion.None) }; - - #endregion - - #region Public Properties - - /// - /// This ensures that the database exists, then runs the base method - /// - public override bool CanConnect - { - get - { - using (var sqlHelper = SqlHelper) - sqlHelper.CreateEmptyDatabase(); - return base.CanConnect; - } - } - - /// - /// Gets a value indicating whether the installer can upgrade the data source. - /// - /// - /// true if the installer can upgrade the data source; otherwise, false. - /// - /// Empty data sources can't be upgraded, just installed. - public override bool CanUpgrade - { - get - { - return CurrentVersion == DatabaseVersion.Version4_1; - } - } - - #endregion - - #region Protected Properties - - /// - /// Gets the version specification for evaluation by DetermineCurrentVersion. - /// Only first matching specification is taken into account. - /// - /// The version specifications. - protected override VersionSpecs[] VersionSpecs - { - get { return m_VersionSpecs; } - } - - #endregion - - #region Public Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The SQL helper. - public SqlCEInstaller(SqlCEHelper sqlHelper) : base(sqlHelper, LatestVersionSupported) - { } - - #endregion - - #region DefaultInstaller Members - - /// - /// Returns the sql to do a full install - /// - protected override string FullInstallSql - { - get { return string.Empty; } - } - - - /// - /// Returns the sql to do an upgrade - /// - protected override string UpgradeSql - { - get { return string.Empty; } - } - - // We need to override this as the default way of detection a db connection checks for systables that doesn't exist - // in a CE db - protected override DatabaseVersion DetermineCurrentVersion() - { - DatabaseVersion version = base.DetermineCurrentVersion(); - if (version != DatabaseVersion.Unavailable) - { - return version; - } - - // verify connection - try - { - using (var sqlHelper = SqlHelper) - if (SqlCeApplicationBlock.VerifyConnection(sqlHelper.ConnectionString)) - return DatabaseVersion.None; - } - catch (Exception e) - { - Trace.WriteLine(e.ToString()); - } - - return DatabaseVersion.Unavailable; - } - - #endregion - } -} diff --git a/src/SQLCE4Umbraco/SqlCEParameter.cs b/src/SQLCE4Umbraco/SqlCEParameter.cs deleted file mode 100644 index 9aa0b4c400..0000000000 --- a/src/SQLCE4Umbraco/SqlCEParameter.cs +++ /dev/null @@ -1,34 +0,0 @@ -/************************************************************************************ - * - * Umbraco Data Layer - * MIT Licensed work - * ©2008 Ruben Verborgh - * - ***********************************************************************************/ - -using System; -using System.Data.SqlServerCe; -using System.Data.SqlTypes; -using umbraco.DataLayer; - -namespace SqlCE4Umbraco -{ - /// - /// Parameter class for the SqlCEHelper. - /// - public class SqlCEParameter : SqlParameterAdapter - { - #region Public Constructors - - /// - /// Initializes a new instance of the class. - /// - /// Name of the parameter. - /// Value of the parameter. - public SqlCEParameter(string parameterName, object value) - : base(new SqlCeParameter(parameterName, value)) - { } - - #endregion - } -} diff --git a/src/SQLCE4Umbraco/SqlCETableUtility.cs b/src/SQLCE4Umbraco/SqlCETableUtility.cs deleted file mode 100644 index cac6e0d784..0000000000 --- a/src/SQLCE4Umbraco/SqlCETableUtility.cs +++ /dev/null @@ -1,250 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using umbraco.DataLayer.Utility.Table; -using umbraco.DataLayer; -using umbraco; - -namespace SqlCE4Umbraco -{ - /// - /// SQL Server implementation of . - /// - [Obsolete("The legacy installers are no longer used and will be removed from the codebase in the future")] - public class SqlCETableUtility : DefaultTableUtility - { - /// - /// Initializes a new instance of the class. - /// - /// The SQL helper. - public SqlCETableUtility(SqlCEHelper sqlHelper) - : base(sqlHelper) - { } - - #region DefaultTableUtility members - - /// - /// Gets the table with the specified name. - /// - /// The name. - /// The table, or null if no table with that name exists. - public override ITable GetTable(string name) - { - if (name == null) - throw new ArgumentNullException("name"); - - ITable table = null; - - // get name in correct casing - using (var sqlHelper = SqlHelper) - name = sqlHelper.ExecuteScalar("SELECT name FROM sys.tables WHERE name=@name", - sqlHelper.CreateParameter("name", name)); - if (name != null) - { - table = new DefaultTable(name); - - using (var sqlHelper = SqlHelper) - using (IRecordsReader reader = sqlHelper.ExecuteReader( - @"SELECT c.name AS Name, st.name AS DataType, c.max_length, c.is_nullable, c.is_identity - FROM sys.tables AS t - JOIN sys.columns AS c ON t.object_id = c.object_id - JOIN sys.schemas AS s ON s.schema_id = t.schema_id - JOIN sys.types AS ty ON ty.user_type_id = c.user_type_id - JOIN sys.types st ON ty.system_type_id = st.user_type_id - WHERE t.name = @name - ORDER BY c.column_id", sqlHelper.CreateParameter("name", name))) - { - while (reader.Read()) - { - table.AddField(table.CreateField(reader.GetString("Name"), GetType(reader))); - } - } - } - - return table; - } - - /// - /// Saves or updates the table. - /// - /// The table to be saved. - public override void SaveTable(ITable table) - { - if (table == null) - throw new ArgumentNullException("table"); - - ITable oldTable = GetTable(table.Name); - - // create the table if it didn't exist, update fields otherwise - if (oldTable == null) - { - CreateTable(table); - } - else - { - foreach (IField field in table) - { - // create the field if it did't exist in the old table - if (oldTable.FindField(field.Name)==null) - { - CreateColumn(table, field); - } - } - } - } - - #endregion - - #region Protected Helper Methods - - /// - /// Creates the table in the data source. - /// - /// The table. - protected virtual void CreateTable(ITable table) - { - Debug.Assert(table != null); - - // create enumerator and check for first field - IEnumerator fieldEnumerator = table.GetEnumerator(); - bool hasNext = fieldEnumerator.MoveNext(); - if(!hasNext) - throw new ArgumentException("The table must contain at least one field."); - - // create query - StringBuilder createTableQuery = new StringBuilder(); - using (var sqlHelper = SqlHelper) - createTableQuery.AppendFormat("CREATE TABLE [{0}] (", sqlHelper.EscapeString(table.Name)); - - // add fields - while (hasNext) - { - // add field name and type - IField field = fieldEnumerator.Current; - createTableQuery.Append('[').Append(field.Name).Append(']'); - createTableQuery.Append(' ').Append(GetDatabaseType(field)); - - // append comma if a following field exists - hasNext = fieldEnumerator.MoveNext(); - if (hasNext) - { - createTableQuery.Append(','); - } - } - - // close CREATE TABLE x (...) bracket - createTableQuery.Append(')'); - - // execute query - try - { - using (var sqlHelper = SqlHelper) - sqlHelper.ExecuteNonQuery(createTableQuery.ToString()); - } - catch (Exception executeException) - { - throw new UmbracoException(String.Format("Could not create table '{0}'.", table), executeException); - } - } - - /// - /// Creates a new column in the table. - /// - /// The table. - /// The field used to create the column. - protected virtual void CreateColumn(ITable table, IField field) - { - Debug.Assert(table != null && field != null); - - StringBuilder addColumnQuery = new StringBuilder(); - using (var sqlHelper = SqlHelper) - addColumnQuery.AppendFormat("ALTER TABLE [{0}] ADD [{1}] {2}", - sqlHelper.EscapeString(table.Name), - sqlHelper.EscapeString(field.Name), - sqlHelper.EscapeString(GetDatabaseType(field))); - try - { - using (var sqlHelper = SqlHelper) - sqlHelper.ExecuteNonQuery(addColumnQuery.ToString()); - } - catch (Exception executeException) - { - throw new UmbracoException(String.Format("Could not create column '{0}' in table '{1}'.", - field, table.Name), executeException); - } - } - - /// - /// Gets the .Net type corresponding to the specified database data type. - /// - /// The data type reader. - /// The .Net type - protected virtual Type GetType(IRecordsReader dataTypeReader) - { - string typeName = dataTypeReader.GetString("DataType"); - - switch (typeName) - { - case "bit": return typeof(bool); - case "tinyint": return typeof(byte); - case "datetime": return typeof(DateTime); - // TODO: return different decimal type according to field precision - case "decimal": return typeof(decimal); - case "uniqueidentifier": return typeof(Guid); - case "smallint": return typeof(Int16); - case "int": return typeof(Int32); - case "bigint": return typeof(Int64); - case "nvarchar": return typeof(string); - default: - throw new ArgumentException(String.Format("Cannot convert database type '{0}' to a .Net type.", - typeName)); - } - } - - /// - /// Gets the database type corresponding to the field, complete with field properties. - /// - /// The field. - /// The database type. - protected virtual string GetDatabaseType(IField field) - { - StringBuilder fieldBuilder = new StringBuilder(); - - fieldBuilder.Append(GetDatabaseTypeName(field)); - fieldBuilder.Append(field.HasProperty(FieldProperties.Identity) ? " IDENTITY(1,1)" : String.Empty); - fieldBuilder.Append(field.HasProperty(FieldProperties.NotNull) ? " NOT NULL" : " NULL"); - - return fieldBuilder.ToString(); - } - - /// - /// Gets the name of the database type, without field properties. - /// - /// The field. - /// - protected virtual string GetDatabaseTypeName(IField field) - { - switch (field.DataType.FullName) - { - case "System.Boolean": return "bit"; - case "System.Byte": return "tinyint"; - case "System.DateTime": return "datetime"; - case "System.Decimal": return "decimal(28)"; - case "System.Double": return "decimal(15)"; - case "System.Single": return "decimal(7)"; - case "System.Guid": return "uniqueidentifier"; - case "System.Int16": return "smallint"; - case "System.Int32": return "int"; - case "System.Int64": return "bigint";; - case "System.String": - string type = "nvarchar"; - return field.Size == 0 ? type : String.Format("{0}({1})", type, field.Size); - default: - throw new ArgumentException(String.Format("Cannot convert '{0}' to a database type.", field)); - } - } - - #endregion - } -} diff --git a/src/SQLCE4Umbraco/SqlCEUtility.cs b/src/SQLCE4Umbraco/SqlCEUtility.cs deleted file mode 100644 index ff6905df10..0000000000 --- a/src/SQLCE4Umbraco/SqlCEUtility.cs +++ /dev/null @@ -1,56 +0,0 @@ -/************************************************************************************ - * - * Umbraco Data Layer - * MIT Licensed work - * ©2008 Ruben Verborgh - * - ***********************************************************************************/ - -using System; -using umbraco.DataLayer.SqlHelpers.SqlServer; -using umbraco.DataLayer.Utility; -using umbraco.DataLayer.Utility.Installer; -using umbraco.DataLayer.Utility.Table; - -namespace SqlCE4Umbraco -{ - /// - /// Utility for an SQL Server data source. - /// - [Obsolete("The legacy installers are no longer used and will be removed from the codebase in the future")] - public class SqlCEUtility : DefaultUtility - { - #region Public Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The SQL helper. - public SqlCEUtility(SqlCEHelper sqlHelper) : base(sqlHelper) - { } - - #endregion - - #region DefaultUtility Members - - /// - /// Creates an installer. - /// - /// The SQL Server installer. - public override IInstallerUtility CreateInstaller() - { - return new SqlCEInstaller(SqlHelper); - } - - /// - /// Creates a table utility. - /// - /// The table utility - public override ITableUtility CreateTableUtility() - { - return new SqlCETableUtility(SqlHelper); - } - - #endregion - } -} diff --git a/src/SQLCE4Umbraco/SqlCeApplicationBlock.cs b/src/SQLCE4Umbraco/SqlCeApplicationBlock.cs deleted file mode 100644 index 2dd0f26e90..0000000000 --- a/src/SQLCE4Umbraco/SqlCeApplicationBlock.cs +++ /dev/null @@ -1,270 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data.SqlServerCe; -using System.Data; -using System.Diagnostics; -using SQLCE4Umbraco; - -namespace SqlCE4Umbraco -{ - public class SqlCeApplicationBlock - { - /// - /// - /// - /// - /// - /// - /// - /// - public static object ExecuteScalar( - string connectionString, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters - ) - { - try - { - using (var conn = SqlCeContextGuardian.Open(connectionString)) - { - return ExecuteScalarTry(conn, null, commandText, commandParameters); - } - } - catch (Exception ee) - { - throw new SqlCeProviderException("Error running Scalar: \nSQL Statement:\n" + commandText + "\n\nException:\n" + ee); - } - } - - public static object ExecuteScalar( - SqlCeConnection conn, SqlCeTransaction trx, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters) - { - try - { - return ExecuteScalarTry(conn, trx, commandText, commandParameters); - } - catch (Exception ee) - { - throw new SqlCeProviderException("Error running Scalar: \nSQL Statement:\n" + commandText + "\n\nException:\n" + ee); - } - } - - public static object ExecuteScalar( - SqlCeConnection conn, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters) - { - return ExecuteScalar(conn, null, commandType, commandText, commandParameters); - } - - private static object ExecuteScalarTry( - SqlCeConnection conn, SqlCeTransaction trx, - string commandText, - params SqlCeParameter[] commandParameters) - { - object retVal; - using (var cmd = trx == null ? new SqlCeCommand(commandText, conn) : new SqlCeCommand(commandText, conn, trx)) - { - AttachParameters(cmd, commandParameters); - Debug.WriteLine("---------------------------------SCALAR-------------------------------------"); - Debug.WriteLine(commandText); - Debug.WriteLine("----------------------------------------------------------------------------"); - retVal = cmd.ExecuteScalar(); - } - return retVal; - } - - /// - /// - /// - /// - /// - /// - /// - public static int ExecuteNonQuery( - string connectionString, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters - ) - { - try - { - using (var conn = SqlCeContextGuardian.Open(connectionString)) - { - return ExecuteNonQueryTry(conn, null, commandText, commandParameters); - } - } - catch (Exception ee) - { - throw new SqlCeProviderException("Error running NonQuery: \nSQL Statement:\n" + commandText + "\n\nException:\n" + ee.ToString()); - } - } - - public static int ExecuteNonQuery( - SqlCeConnection conn, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters - ) - { - return ExecuteNonQuery(conn, null, commandType, commandText, commandParameters); - } - - public static int ExecuteNonQuery( - SqlCeConnection conn, SqlCeTransaction trx, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters - ) - { - try - { - return ExecuteNonQueryTry(conn, trx, commandText, commandParameters); - } - catch (Exception ee) - { - throw new SqlCeProviderException("Error running NonQuery: \nSQL Statement:\n" + commandText + "\n\nException:\n" + ee.ToString()); - } - } - - private static int ExecuteNonQueryTry( - SqlCeConnection conn, SqlCeTransaction trx, - string commandText, - params SqlCeParameter[] commandParameters) - { - // this is for multiple queries in the installer - if (commandText.Trim().StartsWith("!!!")) - { - commandText = commandText.Trim().Trim('!'); - var commands = commandText.Split('|'); - var currentCmd = string.Empty; - - foreach (var command in commands) - { - try - { - currentCmd = command; - if (string.IsNullOrWhiteSpace(command)) continue; - var c = trx == null ? new SqlCeCommand(command, conn) : new SqlCeCommand(command, conn, trx); - c.ExecuteNonQuery(); - } - catch (Exception e) - { - Debug.WriteLine("*******************************************************************"); - Debug.WriteLine(currentCmd); - Debug.WriteLine(e); - Debug.WriteLine("*******************************************************************"); - } - } - return 1; - } - - Debug.WriteLine("----------------------------------------------------------------------------"); - Debug.WriteLine(commandText); - Debug.WriteLine("----------------------------------------------------------------------------"); - var cmd = new SqlCeCommand(commandText, conn); - AttachParameters(cmd, commandParameters); - var rowsAffected = cmd.ExecuteNonQuery(); - return rowsAffected; - } - - /// - /// - /// - /// - /// - /// - /// - /// - public static SqlCeDataReader ExecuteReader( - string connectionString, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters - ) - { - try - { - var conn = SqlCeContextGuardian.Open(connectionString); - return ExecuteReaderTry(conn, null, commandText, commandParameters); - } - catch (Exception ee) - { - throw new SqlCeProviderException("Error running Reader: \nSQL Statement:\n" + commandText + "\n\nException:\n" + ee.ToString()); - } - } - - public static SqlCeDataReader ExecuteReader( - SqlCeConnection conn, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters - ) - { - return ExecuteReader(conn, commandType, commandText, commandParameters); - } - - public static SqlCeDataReader ExecuteReader( - SqlCeConnection conn, SqlCeTransaction trx, - CommandType commandType, - string commandText, - params SqlCeParameter[] commandParameters - ) - { - try - { - return ExecuteReaderTry(conn, trx, commandText, commandParameters); - } - catch (Exception ee) - { - throw new SqlCeProviderException("Error running Reader: \nSQL Statement:\n" + commandText + "\n\nException:\n" + ee.ToString()); - } - } - - private static SqlCeDataReader ExecuteReaderTry( - SqlCeConnection conn, SqlCeTransaction trx, - string commandText, - params SqlCeParameter[] commandParameters) - { - Debug.WriteLine("---------------------------------READER-------------------------------------"); - Debug.WriteLine(commandText); - Debug.WriteLine("----------------------------------------------------------------------------"); - - try - { - var cmd = trx == null ? new SqlCeCommand(commandText, conn) : new SqlCeCommand(commandText, conn, trx); - AttachParameters(cmd, commandParameters); - return cmd.ExecuteReader(); - } - catch - { - conn.Close(); - throw; - } - } - - public static bool VerifyConnection(string connectionString) - { - using (var conn = SqlCeContextGuardian.Open(connectionString)) - { - return conn.State == ConnectionState.Open; - } - } - - private static void AttachParameters(SqlCeCommand command, IEnumerable commandParameters) - { - foreach (var parameter in commandParameters) - { - if ((parameter.Direction == ParameterDirection.InputOutput) && (parameter.Value == null)) - parameter.Value = DBNull.Value; - command.Parameters.Add(parameter); - } - } - } -} diff --git a/src/SQLCE4Umbraco/SqlCeContextGuardian.cs b/src/SQLCE4Umbraco/SqlCeContextGuardian.cs deleted file mode 100644 index 8206ac6c53..0000000000 --- a/src/SQLCE4Umbraco/SqlCeContextGuardian.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlServerCe; -using System.Linq; -using System.Text; - -namespace SQLCE4Umbraco -{ - public static class SqlCeContextGuardian - { - private static SqlCeConnection _constantOpenConnection; - private static readonly object Lock = new object(); - - // Awesome SQL CE 4 speed improvement by Erik Ejskov Jensen - SQL CE 4 MVP - // It's not an issue with SQL CE 4 that we never close the connection - public static SqlCeConnection Open(string connectionString) - { - var connectionStringBuilder = new DbConnectionStringBuilder(); - try - { - connectionStringBuilder.ConnectionString = connectionString; - } - catch (Exception ex) - { - throw new ArgumentException("Bad connection string.", "connectionString", ex); - } - connectionStringBuilder.Remove("datalayer"); - - // SQL CE 4 performs better when there's always a connection open in the background - EnsureOpenBackgroundConnection(connectionStringBuilder.ConnectionString); - - SqlCeConnection conn = new SqlCeConnection(connectionStringBuilder.ConnectionString); - conn.Open(); - - return conn; - - } - - /// - /// Sometimes we need to ensure this is closed especially in unit tests - /// - internal static void CloseBackgroundConnection() - { - if (_constantOpenConnection != null) - _constantOpenConnection.Close(); - } - - private static void EnsureOpenBackgroundConnection(string connectionString) - { - lock (Lock) - { - if (_constantOpenConnection == null) - { - _constantOpenConnection = new SqlCeConnection(connectionString); - _constantOpenConnection.Open(); - } - else if (_constantOpenConnection.State != ConnectionState.Open) - _constantOpenConnection.Open(); - } - } - } -} diff --git a/src/SQLCE4Umbraco/SqlCeProviderException.cs b/src/SQLCE4Umbraco/SqlCeProviderException.cs deleted file mode 100644 index e7c105fd4d..0000000000 --- a/src/SQLCE4Umbraco/SqlCeProviderException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SqlCE4Umbraco -{ - public class SqlCeProviderException : Exception - { - public SqlCeProviderException() : base() - { - - } - - public SqlCeProviderException(string message) : base(message) - { - - } - } -} diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 9a7f4e1a4c..e0a678ff62 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -2,10 +2,8 @@ using System.Linq; using System.Xml; using Moq; using NUnit.Framework; -using umbraco.BusinessLogic; using Umbraco.Core.Cache; using Umbraco.Core.Composing; -using Umbraco.Core.Models.PublishedContent; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using Umbraco.Web; diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs index 2e94816576..db810e778e 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs @@ -13,6 +13,8 @@ using Umbraco.Web.PublishedCache.XmlPublishedCache; using Umbraco.Tests.Testing; using Current = Umbraco.Web.Composing.Current; using LightInject; +using Umbraco.Core.Models; +using Umbraco.Core.Models.Membership; namespace Umbraco.Tests.Cache.PublishedCache { @@ -29,16 +31,29 @@ namespace Umbraco.Tests.Cache.PublishedCache .Append(); } + private IMediaType MakeNewMediaType(IUser user, string text, int parentId = -1) + { + var mt = new MediaType(parentId) { Name = text, Alias = text, Thumbnail = "icon-folder", Icon = "icon-folder" }; + ServiceContext.MediaTypeService.Save(mt); + return mt; + } + + private IMedia MakeNewMedia(string name, IMediaType mediaType, IUser user, int parentId) + { + var m = ServiceContext.MediaService.CreateMediaWithIdentity(name, parentId, mediaType.Alias); + return m; + } + //NOTE: This is "Without_Examine" too [Test] public void Get_Root_Docs() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot1", mType, user, -1); - var mRoot2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot2", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot1.Id); - var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot2.Id); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot1 = MakeNewMedia("MediaRoot1", mType, user, -1); + var mRoot2 = MakeNewMedia("MediaRoot2", mType, user, -1); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot1.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot2.Id); var ctx = GetUmbracoContext("/test"); var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); @@ -52,9 +67,9 @@ namespace Umbraco.Tests.Cache.PublishedCache public void Get_Item_Without_Examine() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); //var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234)); var umbracoContext = GetUmbracoContext("/test"); @@ -63,15 +78,15 @@ namespace Umbraco.Tests.Cache.PublishedCache Assert.IsNotNull(publishedMedia); Assert.AreEqual(mRoot.Id, publishedMedia.Id); - Assert.AreEqual(mRoot.CreateDateTime.ToString("dd/MM/yyyy HH:mm:ss"), publishedMedia.CreateDate.ToString("dd/MM/yyyy HH:mm:ss")); - Assert.AreEqual(mRoot.User.Id, publishedMedia.CreatorId); - Assert.AreEqual(mRoot.User.Name, publishedMedia.CreatorName); + Assert.AreEqual(mRoot.CreateDate.ToString("dd/MM/yyyy HH:mm:ss"), publishedMedia.CreateDate.ToString("dd/MM/yyyy HH:mm:ss")); + Assert.AreEqual(mRoot.CreatorId, publishedMedia.CreatorId); + //Assert.AreEqual(mRoot.User.Name, publishedMedia.CreatorName); Assert.AreEqual(mRoot.ContentType.Alias, publishedMedia.DocumentTypeAlias); Assert.AreEqual(mRoot.ContentType.Id, publishedMedia.DocumentTypeId); Assert.AreEqual(mRoot.Level, publishedMedia.Level); - Assert.AreEqual(mRoot.Text, publishedMedia.Name); + Assert.AreEqual(mRoot.Name, publishedMedia.Name); Assert.AreEqual(mRoot.Path, publishedMedia.Path); - Assert.AreEqual(mRoot.sortOrder, publishedMedia.SortOrder); + Assert.AreEqual(mRoot.SortOrder, publishedMedia.SortOrder); Assert.IsNull(publishedMedia.Parent); } diff --git a/src/Umbraco.Tests/Issues/U9560.cs b/src/Umbraco.Tests/Issues/U9560.cs index 8f690933df..0b8bbfe4d5 100644 --- a/src/Umbraco.Tests/Issues/U9560.cs +++ b/src/Umbraco.Tests/Issues/U9560.cs @@ -79,20 +79,20 @@ namespace Umbraco.Tests.Issues // and now it is OK Assert.AreEqual("alias", aliasName); - // get the legacy content type - var legacyContentType = new umbraco.cms.businesslogic.ContentType(contentType.Id); - Assert.AreEqual("test", legacyContentType.Alias); + //// get the legacy content type + //var legacyContentType = new umbraco.cms.businesslogic.ContentType(contentType.Id); + //Assert.AreEqual("test", legacyContentType.Alias); - // get the legacy properties - var legacyProperties = legacyContentType.PropertyTypes; + //// get the legacy properties + //var legacyProperties = legacyContentType.PropertyTypes; - // without the fix, due to some (swallowed) inner exception, we have no properties - //Assert.IsNull(legacyProperties); + //// without the fix, due to some (swallowed) inner exception, we have no properties + ////Assert.IsNull(legacyProperties); - // thanks to the fix, it works - Assert.IsNotNull(legacyProperties); - Assert.AreEqual(1, legacyProperties.Count); - Assert.AreEqual("prop", legacyProperties[0].Alias); + //// thanks to the fix, it works + //Assert.IsNotNull(legacyProperties); + //Assert.AreEqual(1, legacyProperties.Count); + //Assert.AreEqual("prop", legacyProperties[0].Alias); } } } diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 5a76a540ef..ff349d41fe 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -1,23 +1,13 @@ using System; -using System.IO; -using System.Web.Caching; using System.Web.UI; using System.Web.UI.WebControls; -using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Logging; -using Umbraco.Core.Profiling; -using umbraco; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; -using Umbraco.Web; using Umbraco.Web.Macros; -using File = System.IO.File; -using Macro = umbraco.cms.businesslogic.macro.Macro; -using Current = Umbraco.Core.Composing.Current; namespace Umbraco.Tests.Macros { diff --git a/src/Umbraco.Tests/Migrations/Upgrades/SqlCeDataUpgradeTest.cs b/src/Umbraco.Tests/Migrations/Upgrades/SqlCeDataUpgradeTest.cs index 3af2f6f3c4..6676e010ec 100644 --- a/src/Umbraco.Tests/Migrations/Upgrades/SqlCeDataUpgradeTest.cs +++ b/src/Umbraco.Tests/Migrations/Upgrades/SqlCeDataUpgradeTest.cs @@ -3,7 +3,6 @@ using Moq; using NPoco; using NUnit.Framework; using Semver; -using SQLCE4Umbraco; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; @@ -59,7 +58,7 @@ namespace Umbraco.Tests.Migrations.Upgrades public override void DatabaseSpecificTearDown() { //legacy API database connection close - SqlCeContextGuardian.CloseBackgroundConnection(); + //SqlCeContextGuardian.CloseBackgroundConnection(); } public override IUmbracoDatabase GetConfiguredDatabase() diff --git a/src/Umbraco.Tests/Migrations/Upgrades/SqlCeUpgradeTest.cs b/src/Umbraco.Tests/Migrations/Upgrades/SqlCeUpgradeTest.cs index bb0b3859df..052cf130e4 100644 --- a/src/Umbraco.Tests/Migrations/Upgrades/SqlCeUpgradeTest.cs +++ b/src/Umbraco.Tests/Migrations/Upgrades/SqlCeUpgradeTest.cs @@ -6,7 +6,6 @@ using System.IO; using Moq; using NPoco; using NUnit.Framework; -using SQLCE4Umbraco; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; @@ -22,6 +21,9 @@ namespace Umbraco.Tests.Migrations.Upgrades { string filePath = string.Concat(Path, "\\UmbracoNPocoTests.sdf"); + // no more "clear database" just recreate it + if (File.Exists(filePath)) File.Delete(filePath); + if (!File.Exists(filePath)) { try @@ -50,7 +52,7 @@ namespace Umbraco.Tests.Migrations.Upgrades } else { - TestHelper.ClearDatabase(); + //TestHelper.ClearDatabase(); } } @@ -58,9 +60,9 @@ namespace Umbraco.Tests.Migrations.Upgrades public override void DatabaseSpecificTearDown() { //legacy API database connection close - SqlCeContextGuardian.CloseBackgroundConnection(); + //SqlCeContextGuardian.CloseBackgroundConnection(); - TestHelper.ClearDatabase(); + //TestHelper.ClearDatabase(); } public override IUmbracoDatabase GetConfiguredDatabase() diff --git a/src/Umbraco.Tests/Migrations/Upgrades/ValidateOlderSchemaTest.cs b/src/Umbraco.Tests/Migrations/Upgrades/ValidateOlderSchemaTest.cs index 9a031069ff..024ba2b466 100644 --- a/src/Umbraco.Tests/Migrations/Upgrades/ValidateOlderSchemaTest.cs +++ b/src/Umbraco.Tests/Migrations/Upgrades/ValidateOlderSchemaTest.cs @@ -7,9 +7,7 @@ using System.Text.RegularExpressions; using Moq; using NPoco; using NUnit.Framework; -using SQLCE4Umbraco; using Umbraco.Core; -using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Migrations.Initial; @@ -86,7 +84,7 @@ namespace Umbraco.Tests.Migrations.Upgrades AppDomain.CurrentDomain.SetData("DataDirectory", null); //legacy API database connection close - SqlCeContextGuardian.CloseBackgroundConnection(); + //SqlCeContextGuardian.CloseBackgroundConnection(); string filePath = string.Concat(Path, "\\UmbracoNPocoTests.sdf"); if (File.Exists(filePath)) diff --git a/src/Umbraco.Tests/Plugins/PluginManagerTests.cs b/src/Umbraco.Tests/Plugins/PluginManagerTests.cs index 251120d12b..f53d07eedd 100644 --- a/src/Umbraco.Tests/Plugins/PluginManagerTests.cs +++ b/src/Umbraco.Tests/Plugins/PluginManagerTests.cs @@ -6,18 +6,12 @@ using System.Linq; using System.Reflection; using Moq; using NUnit.Framework; -using SqlCE4Umbraco; using umbraco; - -using umbraco.cms.businesslogic; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.IO; using Umbraco.Core.Logging; -using Umbraco.Core.Profiling; using Umbraco.Core.PropertyEditors; -using umbraco.DataLayer; -using umbraco.uicontrols; using Umbraco.Core.Composing; using Umbraco.Web; using Umbraco.Web.PropertyEditors; @@ -41,18 +35,15 @@ namespace Umbraco.Tests.Plugins _manager.AssembliesToScan = new[] { this.GetType().Assembly, - typeof(SqlCEHelper).Assembly, - typeof(CMSNode).Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, - typeof(TabPage).Assembly, + //typeof(TabPage).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(TypeFinder).Assembly, - typeof(ISqlHelper).Assembly, typeof(UmbracoContext).Assembly }; } diff --git a/src/Umbraco.Tests/Plugins/TypeFinderTests.cs b/src/Umbraco.Tests/Plugins/TypeFinderTests.cs index 0a6d2d677c..c7102337e2 100644 --- a/src/Umbraco.Tests/Plugins/TypeFinderTests.cs +++ b/src/Umbraco.Tests/Plugins/TypeFinderTests.cs @@ -11,20 +11,13 @@ using System.Threading; using System.Web; using System.Web.Compilation; using NUnit.Framework; -using SqlCE4Umbraco; using umbraco; - -using umbraco.cms.businesslogic; using Umbraco.Core; using Umbraco.Core.IO; -using umbraco.DataLayer; -using umbraco.uicontrols; using Umbraco.Core.Logging; using Umbraco.Core.Composing; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Web; -using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; namespace Umbraco.Tests.Plugins @@ -47,18 +40,15 @@ namespace Umbraco.Tests.Plugins _assemblies = new[] { this.GetType().Assembly, - typeof(SqlCEHelper).Assembly, - typeof(CMSNode).Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, - typeof(TabPage).Assembly, + //typeof(TabPage).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(TypeFinder).Assembly, - typeof(ISqlHelper).Assembly, typeof(global::UmbracoExamine.BaseUmbracoIndexer).Assembly }; diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index 9b43e14b8e..f1dc630271 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -20,6 +20,7 @@ using UmbracoExamine; using Current = Umbraco.Web.Composing.Current; using Umbraco.Tests.Testing; using LightInject; +using Umbraco.Core.Models.Membership; namespace Umbraco.Tests.PublishedContent { @@ -42,6 +43,19 @@ namespace Umbraco.Tests.PublishedContent .Append(); } + private IMediaType MakeNewMediaType(IUser user, string text, int parentId = -1) + { + var mt = new MediaType(parentId) { Name = text, Alias = text, Thumbnail = "icon-folder", Icon = "icon-folder" }; + ServiceContext.MediaTypeService.Save(mt); + return mt; + } + + private IMedia MakeNewMedia(string name, IMediaType mediaType, IUser user, int parentId) + { + var m = ServiceContext.MediaService.CreateMediaWithIdentity(name, parentId, mediaType.Alias); + return m; + } + /// /// Shared with PublishMediaStoreTests /// @@ -290,16 +304,16 @@ namespace Umbraco.Tests.PublishedContent public void Children_Without_Examine() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); - var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); - var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); var publishedMedia = GetNode(mRoot.Id); var rootChildren = publishedMedia.Children(); @@ -314,16 +328,16 @@ namespace Umbraco.Tests.PublishedContent public void Descendants_Without_Examine() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); - var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); - var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); var publishedMedia = GetNode(mRoot.Id); var rootDescendants = publishedMedia.Descendants(); @@ -338,16 +352,16 @@ namespace Umbraco.Tests.PublishedContent public void DescendantsOrSelf_Without_Examine() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); - var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); - var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); var publishedMedia = GetNode(mRoot.Id); var rootDescendantsOrSelf = publishedMedia.DescendantsOrSelf(); @@ -364,16 +378,16 @@ namespace Umbraco.Tests.PublishedContent public void Parent_Without_Examine() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); - var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); - var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); var publishedRoot = GetNode(mRoot.Id); Assert.AreEqual(null, publishedRoot.Parent); @@ -389,16 +403,16 @@ namespace Umbraco.Tests.PublishedContent public void Ancestors_Without_Examine() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); - var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); - var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); var publishedSubChild1 = GetNode(mSubChild1.Id); Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mRoot.Id })); @@ -408,16 +422,16 @@ namespace Umbraco.Tests.PublishedContent public void AncestorsOrSelf_Without_Examine() { var user = ServiceContext.UserService.GetUserById(0); - var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); - var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); - var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); - var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); var publishedSubChild1 = GetNode(mSubChild1.Id); Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id).ContainsAll( diff --git a/src/Umbraco.Tests/Templates/MasterPageHelperTests.cs b/src/Umbraco.Tests/Templates/MasterPageHelperTests.cs index 6da4fbc07e..ce369f7ea6 100644 --- a/src/Umbraco.Tests/Templates/MasterPageHelperTests.cs +++ b/src/Umbraco.Tests/Templates/MasterPageHelperTests.cs @@ -1,11 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; -using umbraco.cms.businesslogic.template; +using NUnit.Framework; using Umbraco.Core.IO; -using Umbraco.Core.Services; namespace Umbraco.Tests.Templates { diff --git a/src/Umbraco.Tests/TestHelpers/TestHelper.cs b/src/Umbraco.Tests/TestHelpers/TestHelper.cs index b9fe35cb21..fec5b7f801 100644 --- a/src/Umbraco.Tests/TestHelpers/TestHelper.cs +++ b/src/Umbraco.Tests/TestHelpers/TestHelper.cs @@ -8,10 +8,8 @@ using System.Linq; using System.Reflection; using System.Threading; using NUnit.Framework; -using SqlCE4Umbraco; using Umbraco.Core; using Umbraco.Core.IO; -using umbraco.DataLayer; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Tests.TestHelpers @@ -22,30 +20,7 @@ namespace Umbraco.Tests.TestHelpers public static class TestHelper { - /// - /// Clears an initialized database - /// - public static void ClearDatabase() - { - var databaseSettings = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName]; - var dataHelper = DataLayerHelper.CreateSqlHelper(databaseSettings.ConnectionString, false) as SqlCEHelper; - - if (dataHelper == null) - throw new InvalidOperationException("The sql helper for unit tests must be of type SqlCEHelper, check the ensure the connection string used for this test is set to use SQLCE"); - - dataHelper.ClearDatabase(); - } - - public static void DropForeignKeys(string table) - { - var databaseSettings = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName]; - var dataHelper = DataLayerHelper.CreateSqlHelper(databaseSettings.ConnectionString, false) as SqlCEHelper; - - if (dataHelper == null) - throw new InvalidOperationException("The sql helper for unit tests must be of type SqlCEHelper, check the ensure the connection string used for this test is set to use SQLCE"); - - dataHelper.DropForeignKeys(table); - } + /// /// Gets the current assembly directory. diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index d6c4666441..285b45e281 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -7,7 +7,6 @@ using System.Web.Routing; using System.Xml; using Moq; using NUnit.Framework; -using SQLCE4Umbraco; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; @@ -300,7 +299,7 @@ namespace Umbraco.Tests.TestHelpers //Ensure that any database connections from a previous test is disposed. //This is really just double safety as its also done in the TearDown. database?.Dispose(); - SqlCeContextGuardian.CloseBackgroundConnection(); + //SqlCeContextGuardian.CloseBackgroundConnection(); } private void RemoveDatabaseFile(IUmbracoDatabase database, Action onFail = null) diff --git a/src/Umbraco.Tests/TreesAndSections/SectionTests.cs b/src/Umbraco.Tests/TreesAndSections/SectionTests.cs index 310adec594..89f21e1fe7 100644 --- a/src/Umbraco.Tests/TreesAndSections/SectionTests.cs +++ b/src/Umbraco.Tests/TreesAndSections/SectionTests.cs @@ -2,7 +2,6 @@ using NUnit.Framework; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers; -using umbraco.BusinessLogic; using System; using System.Linq; using Umbraco.Core; diff --git a/src/Umbraco.Tests/UI/LegacyDialogTests.cs b/src/Umbraco.Tests/UI/LegacyDialogTests.cs index 6ea66761e3..9afe8dbe42 100644 --- a/src/Umbraco.Tests/UI/LegacyDialogTests.cs +++ b/src/Umbraco.Tests/UI/LegacyDialogTests.cs @@ -1,12 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Web.UI; using umbraco; -using umbraco.BusinessLogic; using umbraco.cms.presentation.user; using Umbraco.Core.Composing; using Umbraco.Web._Legacy.UI; diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index e475dc813a..9cc99c7be7 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -600,26 +600,10 @@ - - {5BA5425F-27A7-4677-865E-82246498AA2E} - SqlCE4Umbraco - - - {CCD75EC3-63DB-4184-B49D-51C1DD337230} - umbraco.cms - - - {6EDD2061-82F2-461B-BB6E-879245A832DE} - umbraco.controls - {31785BC3-256C-4613-B2F5-A1B0BDDED8C1} Umbraco.Core - - {C7CB79F0-1C97-4B33-BFA7-00731B579AE2} - umbraco.datalayer - {651E1350-91B6-44B7-BD60-7207006D7003} Umbraco.Web diff --git a/src/umbraco.cms/Properties/AssemblyInfo.cs b/src/umbraco.cms/Properties/AssemblyInfo.cs deleted file mode 100644 index ca728d05e1..0000000000 --- a/src/umbraco.cms/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// -[assembly: AssemblyTitle("umbraco.cms")] -[assembly: AssemblyDescription("Core assembly containing CMS functionality")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("Umbraco CMS")] - -[assembly: InternalsVisibleTo("umbraco", AllInternalsVisible=true)] -[assembly: InternalsVisibleTo("Umbraco.LegacyTests")] -[assembly: InternalsVisibleTo("Umbraco.Tests")] -[assembly: InternalsVisibleTo("umbraco.editorControls")] \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/CMSNode.cs b/src/umbraco.cms/businesslogic/CMSNode.cs deleted file mode 100644 index af48dd4d31..0000000000 --- a/src/umbraco.cms/businesslogic/CMSNode.cs +++ /dev/null @@ -1,1082 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Xml; -using Umbraco.Core; -using Umbraco.Core.Models.EntityBase; -using Umbraco.Core.Persistence; - -using umbraco.cms.businesslogic.web; -using umbraco.DataLayer; -using umbraco.BusinessLogic; -using System.IO; -using System.Text.RegularExpressions; -using System.ComponentModel; -using Umbraco.Core.IO; -using System.Collections; -using umbraco.cms.businesslogic.task; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; -using File = System.IO.File; - -using Task = umbraco.cms.businesslogic.task.Task; - -namespace umbraco.cms.businesslogic -{ - /// - /// CMSNode class serves as the base class for many of the other components in the cms.businesslogic.xx namespaces. - /// Providing the basic hierarchical data structure and properties Text (name), Creator, Createdate, updatedate etc. - /// which are shared by most umbraco objects. - /// - /// The child classes are required to implement an identifier (Guid) which is used as the objecttype identifier, for - /// distinguishing the different types of CMSNodes (ex. Documents/Medias/Stylesheets/documenttypes and so forth). - /// - [Obsolete("Obsolete, This class will eventually be phased out", false)] - public class CMSNode - { - #region Private Members - - private string _text; - private int _id = 0; - private Guid _uniqueID; - private int _parentid; - private Guid _nodeObjectType; - private int _level; - private string _path; - private bool _hasChildren; - private int _sortOrder; - private int _userId; - private DateTime _createDate; - private bool _hasChildrenInitialized; - private string m_image = "default.png"; - private bool? _isTrashed = null; - protected IUmbracoEntity Entity; - - #endregion - - #region Private static - - - private static readonly List InternalDefaultIconClasses = new List(); - private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(); - - private static void InitializeIconClasses() - { - - } - private const string SqlSingle = "SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text FROM umbracoNode WHERE id = @id"; - private const string SqlDescendants = @" - SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text - FROM umbracoNode - WHERE path LIKE '%,{0},%'"; - - #endregion - - #region Public static - - /// - /// Get a count on all CMSNodes given the objecttype - /// - /// The objecttype identifier - /// - /// The number of CMSNodes of the given objecttype - /// - public static int CountByObjectType(Guid objectType) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return sqlHelper.ExecuteScalar("SELECT COUNT(*) from umbracoNode WHERE nodeObjectType = @type", sqlHelper.CreateParameter("@type", objectType)); - } - - /// - /// Number of ancestors of the current CMSNode - /// - /// The CMSNode Id - /// - /// The number of ancestors from the given CMSNode - /// - public static int CountSubs(int Id) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return sqlHelper.ExecuteScalar("SELECT COUNT(*) FROM umbracoNode WHERE ','+path+',' LIKE '%,@nodeId,%'", - sqlHelper.CreateParameter("nodeId", Id)); - } - - /// - /// Returns the number of leaf nodes from the newParent id for a given object type - /// - /// - /// - /// - public static int CountLeafNodes(int parentId, Guid objectType) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return sqlHelper.ExecuteScalar("Select count(uniqueID) from umbracoNode where nodeObjectType = @type And parentId = @parentId", - sqlHelper.CreateParameter("@type", objectType), - sqlHelper.CreateParameter("@parentId", parentId)); - } - - /// - /// Gets the default icon classes. - /// - /// The default icon classes. - public static List DefaultIconClasses - { - get - { - using (var l = new UpgradeableReadLock(Locker)) - { - if (InternalDefaultIconClasses.Count == 0) - { - l.UpgradeToWriteLock(); - InitializeIconClasses(); - } - return InternalDefaultIconClasses; - } - - } - } - - /// - /// Method for checking if a CMSNode exits with the given Guid - /// - /// Identifier - /// True if there is a CMSNode with the given Guid - public static bool IsNode(Guid uniqueID) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return sqlHelper.ExecuteScalar("select count(id) from umbracoNode where uniqueID = @uniqueID", sqlHelper.CreateParameter("@uniqueId", uniqueID)) > 0; - } - - /// - /// Method for checking if a CMSNode exits with the given id - /// - /// Identifier - /// True if there is a CMSNode with the given id - public static bool IsNode(int Id) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return sqlHelper.ExecuteScalar("select count(id) from umbracoNode where id = @id", sqlHelper.CreateParameter("@id", Id)) > 0; - } - - /// - /// Retrieve a list of the unique id's of all CMSNodes given the objecttype - /// - /// The objecttype identifier - /// - /// A list of all unique identifiers which each are associated to a CMSNode - /// - public static Guid[] getAllUniquesFromObjectType(Guid objectType) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("Select uniqueID from umbracoNode where nodeObjectType = @type", - sqlHelper.CreateParameter("@type", objectType))) - { - System.Collections.ArrayList tmp = new System.Collections.ArrayList(); - - while (dr.Read()) tmp.Add(dr.GetGuid("uniqueID")); - dr.Close(); - - Guid[] retval = new Guid[tmp.Count]; - for (int i = 0; i < tmp.Count; i++) retval[i] = (Guid)tmp[i]; - return retval; - } - } - - /// - /// Retrieve a list of the node id's of all CMSNodes given the objecttype - /// - /// The objecttype identifier - /// - /// A list of all node ids which each are associated to a CMSNode - /// - public static int[] getAllUniqueNodeIdsFromObjectType(Guid objectType) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("Select id from umbracoNode where nodeObjectType = @type", - sqlHelper.CreateParameter("@type", objectType))) - { - System.Collections.ArrayList tmp = new System.Collections.ArrayList(); - - while (dr.Read()) tmp.Add(dr.GetInt("id")); - dr.Close(); - - return (int[])tmp.ToArray(typeof(int)); - } - } - - - /// - /// Retrieves the top level nodes in the hierarchy - /// - /// The Guid identifier of the type of objects - /// - /// A list of all top level nodes given the objecttype - /// - public static Guid[] TopMostNodeIds(Guid ObjectType) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("Select uniqueID from umbracoNode where nodeObjectType = @type And parentId = -1 order by sortOrder", - sqlHelper.CreateParameter("@type", ObjectType))) - { - System.Collections.ArrayList tmp = new System.Collections.ArrayList(); - - while (dr.Read()) tmp.Add(dr.GetGuid("uniqueID")); - dr.Close(); - - Guid[] retval = new Guid[tmp.Count]; - for (int i = 0; i < tmp.Count; i++) retval[i] = (Guid)tmp[i]; - return retval; - } - } - - #endregion - - #region Protected static - - - /// - /// Given the protected modifier the CMSNode.MakeNew method can only be accessed by - /// derived classes > who by definition knows of its own objectType. - /// - /// The newParent CMSNode id - /// The objecttype identifier - /// Creator - /// The level in the tree hieararchy - /// The name of the CMSNode - /// The unique identifier - /// - protected static CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID) - { - CMSNode parent = null; - string path = ""; - int sortOrder = 0; - - if (level > 0) - { - parent = new CMSNode(parentId); - sortOrder = GetNewDocumentSortOrder(parentId); - path = parent.Path; - } - else - path = "-1"; - - // Ruben 8/1/2007: I replace this with a parameterized version. - // But does anyone know what the 'level++' is supposed to be doing there? - // Nothing obviously, since it's a postfix. - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("INSERT INTO umbracoNode(trashed, parentID, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text, createDate) VALUES(@trashed, @parentID, @nodeObjectType, @nodeUser, @level, @path, @sortOrder, @uniqueID, @text, @createDate)", - sqlHelper.CreateParameter("@trashed", 0), - sqlHelper.CreateParameter("@parentID", parentId), - sqlHelper.CreateParameter("@nodeObjectType", objectType), - sqlHelper.CreateParameter("@nodeUser", userId), - sqlHelper.CreateParameter("@level", level++), - sqlHelper.CreateParameter("@path", path), - sqlHelper.CreateParameter("@sortOrder", sortOrder), - sqlHelper.CreateParameter("@uniqueID", uniqueID), - sqlHelper.CreateParameter("@text", text), - sqlHelper.CreateParameter("@createDate", DateTime.Now)); - - CMSNode retVal = new CMSNode(uniqueID); - retVal.Path = path + "," + retVal.Id.ToString(); - - // NH 4.7.1 duplicate permissions because of refactor - if (parent != null) - { - IEnumerable permissions = Permission.GetNodePermissions(parent); - foreach (Permission p in permissions) - { - Permission.MakeNew(Current.Services.UserService.GetUserById(p.UserId), retVal, p.PermissionId); - } - - } - - - return retVal; - } - - private static int GetNewDocumentSortOrder(int parentId) - { - var sortOrder = 0; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader( - "SELECT MAX(sortOrder) AS sortOrder FROM umbracoNode WHERE parentID = @parentID AND nodeObjectType = @GuidForNodesOfTypeDocument", - sqlHelper.CreateParameter("@parentID", parentId), - sqlHelper.CreateParameter("@GuidForNodesOfTypeDocument", Document._objectType) - )) - { - while (dr.Read()) - sortOrder = dr.GetInt("sortOrder") + 1; - } - - return sortOrder; - } - - /// - /// Retrieve a list of the id's of all CMSNodes given the objecttype and the first letter of the name. - /// - /// The objecttype identifier - /// Firstletter - /// - /// A list of all CMSNodes which has the objecttype and a name that starts with the given letter - /// - protected static int[] getUniquesFromObjectTypeAndFirstLetter(Guid objectType, char letter) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("Select id from umbracoNode where nodeObjectType = @objectType AND text like @letter", sqlHelper.CreateParameter("@objectType", objectType), sqlHelper.CreateParameter("@letter", letter.ToString() + "%"))) - { - List tmp = new List(); - while (dr.Read()) tmp.Add(dr.GetInt("id")); - return tmp.ToArray(); - } - } - - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - #endregion - - #region Constructors - - /// - /// Empty constructor that is not suported - /// ...why is it here? - /// - public CMSNode() - { - throw new NotSupportedException(); - } - - /// - /// Initializes a new instance of the class. - /// - /// The id. - public CMSNode(int Id) - { - _id = Id; - setupNode(); - } - - /// - /// This is purely for a hackity hack hack hack in order to make the new Document(id, version) constructor work because - /// the Version property needs to be set on the object before setupNode is called, otherwise it never works! this allows - /// inheritors to set default data before setupNode() is called. - /// - /// - /// - internal CMSNode(int id, object[] ctorArgs) - { - _id = id; - PreSetupNode(ctorArgs); - } - - /// - /// Initializes a new instance of the class. - /// - /// The id. - /// if set to true [no setup]. - public CMSNode(int id, bool noSetup) - { - _id = id; - - if (!noSetup) - setupNode(); - } - - /// - /// Initializes a new instance of the class. - /// - /// The unique ID. - public CMSNode(Guid uniqueID) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - _id = sqlHelper.ExecuteScalar("SELECT id FROM umbracoNode WHERE uniqueID = @uniqueId", sqlHelper.CreateParameter("@uniqueId", uniqueID)); - setupNode(); - } - - public CMSNode(Guid uniqueID, bool noSetup) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - _id = sqlHelper.ExecuteScalar("SELECT id FROM umbracoNode WHERE uniqueID = @uniqueId", sqlHelper.CreateParameter("@uniqueId", uniqueID)); - - if (!noSetup) - setupNode(); - } - - protected internal CMSNode(IRecordsReader reader) - { - _id = reader.GetInt("id"); - PopulateCMSNodeFromReader(reader); - } - - protected internal CMSNode(IUmbracoEntity entity) - { - _id = entity.Id; - Entity = entity; - } - - protected internal CMSNode(IEntity entity) - { - _id = entity.Id; - } - - #endregion - - #region Public Methods - - /// - /// Ensures uniqueness by id - /// - /// - /// - public override bool Equals(object obj) - { - var l = obj as CMSNode; - if (l != null) - { - return this._id.Equals(l._id); - } - return false; - } - - /// - /// Ensures uniqueness by id - /// - /// - public override int GetHashCode() - { - return _id.GetHashCode(); - } - - /// - /// An xml representation of the CMSNOde - /// - /// Xmldocument context - /// If true the xml will append the CMSNodes child xml - /// The CMSNode Xmlrepresentation - public virtual XmlNode ToXml(XmlDocument xd, bool Deep) - { - throw new NotSupportedException("DO NOT USE THIS METHOD, THIS NEEDS TO BE REMOVED FROM THE CODEBASE, REFACTOR ANYTHING THAT IS USING THIS IF YOU GET THIS EXCEPTION"); - } - - public virtual XmlNode ToPreviewXml(XmlDocument xd) - { - // If xml already exists - if (!PreviewExists(UniqueId)) - { - SavePreviewXml(ToXml(xd, false), UniqueId); - } - return GetPreviewXml(xd, UniqueId); - } - - public virtual List GetNodesForPreview(bool childrenOnly) - { - List nodes = new List(); - string sql = @" -select umbracoNode.id, umbracoNode.parentId, umbracoNode.level, umbracoNode.sortOrder, cmsPreviewXml.xml -from umbracoNode -inner join cmsPreviewXml on cmsPreviewXml.nodeId = umbracoNode.id -where trashed = 0 and path like '{0}' -order by level,sortOrder"; - - var pathExp = childrenOnly ? Path + ",%" : Path; - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader(string.Format(sql, pathExp))) - { - while (dr.Read()) - nodes.Add(new CMSPreviewNode(dr.GetInt("id"), dr.GetGuid("uniqueID"), dr.GetInt("parentId"), dr.GetShort("level"), dr.GetInt("sortOrder"), dr.GetString("xml"), false)); - dr.Close(); - - return nodes; - } - } - - /// - /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility - /// - public virtual void Save() - { - - } - - public override string ToString() - { - if (Id != int.MinValue || !string.IsNullOrEmpty(Text)) - { - return string.Format("{{ Id: {0}, Text: {1}, ParentId: {2} }}", - Id, - Text, - _parentid - ); - } - - return base.ToString(); - } - - - [EditorBrowsable(EditorBrowsableState.Never)] - - /// - /// Deletes this instance. - /// - public virtual void delete() - { - - - //removes tasks - foreach (Task t in Tasks) - { - t.Delete(); - } - - //remove permissions - Permission.DeletePermissions(this); - - ////removes tag associations (i know the key is set to cascade but do it anyways) - //Tag.RemoveTagsFromNode(this.Id); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("DELETE FROM umbracoNode WHERE uniqueID= @uniqueId", sqlHelper.CreateParameter("@uniqueId", _uniqueID)); - } - - /// - /// Does the current CMSNode have any child nodes. - /// - /// - /// true if this instance has children; otherwise, false. - /// - public virtual bool HasChildren - { - get - { - if (!_hasChildrenInitialized) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - int tmpChildrenCount = sqlHelper.ExecuteScalar("select count(id) from umbracoNode where ParentId = @id", - sqlHelper.CreateParameter("@id", Id)); - HasChildren = (tmpChildrenCount > 0); - } - } - return _hasChildren; - } - set - { - _hasChildrenInitialized = true; - _hasChildren = value; - } - } - - /// - /// Returns all descendant nodes from this node. - /// - /// - /// - /// This doesn't return a strongly typed IEnumerable object so that we can override in in super clases - /// and since this class isn't a generic (thought it should be) this is not strongly typed. - /// - public virtual IEnumerable GetDescendants() - { - var descendants = new List(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader(string.Format(SqlDescendants, Id))) - { - while (dr.Read()) - { - var node = new CMSNode(dr.GetInt("id"), true); - node.PopulateCMSNodeFromReader(dr); - descendants.Add(node); - } - } - return descendants; - } - - #endregion - - #region Public properties - - /// - /// Determines if the node is in the recycle bin. - /// This is only relavent for node types that support a recyle bin (such as Document/Media) - /// - public virtual bool IsTrashed - { - get - { - if (!_isTrashed.HasValue) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - const string query = "SELECT trashed FROM umbracoNode where id=@id"; - _isTrashed = Convert.ToBoolean(sqlHelper.ExecuteScalar(query, sqlHelper.CreateParameter("@id", this.Id))); - } - } - return _isTrashed.Value; - } - set - { - _isTrashed = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update umbracoNode set trashed = @trashed where id = @id", - sqlHelper.CreateParameter("@trashed", value), - sqlHelper.CreateParameter("@id", this.Id)); - } - } - - /// - /// Gets or sets the sort order. - /// - /// The sort order. - public virtual int sortOrder - { - get { return _sortOrder; } - set - { - _sortOrder = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update umbracoNode set sortOrder = '" + value + "' where id = " + this.Id); - - if (Entity != null) - Entity.SortOrder = value; - } - } - - /// - /// Gets or sets the create date time. - /// - /// The create date time. - public virtual DateTime CreateDateTime - { - get { return _createDate; } - set - { - _createDate = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update umbracoNode set createDate = @createDate where id = " + this.Id, sqlHelper.CreateParameter("@createDate", _createDate)); - } - } - - /// - /// Gets the creator - /// - /// The user. - public IUser User - { - get - { - return Current.Services.UserService.GetUserById(_userId); - } - } - - /// - /// Gets the id. - /// - /// The id. - public int Id - { - get { return _id; } - } - - /// - /// Get the newParent id of the node - /// - public virtual int ParentId - { - get { return _parentid; } - internal set { _parentid = value; } - } - - private IUmbracoEntity _parent; - /// - /// Given the hierarchical tree structure a CMSNode has only one newParent but can have many children - /// - /// The newParent. - public CMSNode Parent - { - get - { - if (Level == 1) throw new ArgumentException("No newParent node"); - if (_parent == null) - { - _parent = Current.Services.EntityService.Get(_parentid); - } - return new CMSNode(_parent); - } - set - { - _parentid = value.Id; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update umbracoNode set parentId = " + value.Id + " where id = " + this.Id.ToString()); - - if (Entity != null) - Entity.ParentId = value.Id; - - _parent = value.Entity; - } - } - - /// - /// An comma separated string consisting of integer node id's - /// that indicates the path from the topmost node to the given node - /// - /// The path. - public virtual string Path - { - get { return _path; } - set - { - _path = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update umbracoNode set path = '" + _path + "' where id = " + this.Id.ToString()); - - if (Entity != null) - Entity.Path = value; - } - } - - /// - /// Returns an integer value that indicates in which level of the - /// tree structure the given node is - /// - /// The level. - public virtual int Level - { - get { return _level; } - set - { - _level = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update umbracoNode set level = " + _level.ToString() + " where id = " + this.Id.ToString()); - - if (Entity != null) - Entity.Level = value; - } - } - - /// - /// All CMSNodes has an objecttype ie. Webpage, StyleSheet etc., used to distinguish between the different - /// object types for for fast loading children to the tree. - /// - /// The type of the node object. - public Guid nodeObjectType - { - get { return _nodeObjectType; } - } - - /// - /// Returns all tasks associated with this node - /// - public Tasks Tasks - { - get { return Task.GetTasks(this.Id); } - } - - public virtual int ChildCount - { - get - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return sqlHelper.ExecuteScalar("SELECT COUNT(*) FROM umbracoNode where ParentID = @parentId", - sqlHelper.CreateParameter("@parentId", this.Id)); - } - } - - /// - /// The basic recursive tree pattern - /// - /// The children. - public virtual CMSNode[] Children - { - get - { - System.Collections.ArrayList tmp = new System.Collections.ArrayList(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text FROM umbracoNode WHERE ParentID = @ParentID AND nodeObjectType = @type order by sortOrder", - sqlHelper.CreateParameter("@type", this.nodeObjectType), - sqlHelper.CreateParameter("ParentID", this.Id))) - { - while (dr.Read()) - { - tmp.Add(new CMSNode(dr)); - } - } - - CMSNode[] retval = new CMSNode[tmp.Count]; - - for (int i = 0; i < tmp.Count; i++) - { - retval[i] = (CMSNode)tmp[i]; - } - return retval; - } - } - - /// - /// Retrieve all CMSNodes in the umbraco installation - /// Use with care. - /// - /// The children of all object types. - public CMSNode[] ChildrenOfAllObjectTypes - { - get - { - System.Collections.ArrayList tmp = new System.Collections.ArrayList(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("select id from umbracoNode where ParentID = " + this.Id + " order by sortOrder")) - { - while (dr.Read()) - tmp.Add(dr.GetInt("Id")); - } - - CMSNode[] retval = new CMSNode[tmp.Count]; - - for (int i = 0; i < tmp.Count; i++) - retval[i] = new CMSNode((int)tmp[i]); - - return retval; - } - } - - #region IconI members - - // Unique identifier of the given node - /// - /// Unique identifier of the CMSNode, used when locating data. - /// - public Guid UniqueId - { - get { return _uniqueID; } - } - - /// - /// Human readable name/label - /// - public virtual string Text - { - get { return _text; } - set - { - _text = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("UPDATE umbracoNode SET text = @text WHERE id = @id", - sqlHelper.CreateParameter("@text", value.Trim()), - sqlHelper.CreateParameter("@id", this.Id)); - - if (Entity != null) - Entity.Name = value; - } - } - - /// - /// Not implemented, always returns "about:blank" - /// - public virtual string DefaultEditorURL - { - get { return "about:blank"; } - } - - /// - /// The icon in the tree - /// - public virtual string Image - { - get { return m_image; } - set { m_image = value; } - - } - - /// - /// The "open/active" icon in the tree - /// - public virtual string OpenImage - { - get { return ""; } - } - - #endregion - - #endregion - - #region Protected methods - - /// - /// This allows inheritors to set the underlying text property without persisting the change to the database. - /// - /// - protected void SetText(string txt) - { - _text = txt; - - if (Entity != null) - Entity.Name = txt; - } - - /// - /// This is purely for a hackity hack hack hack in order to make the new Document(id, version) constructor work because - /// the Version property needs to be set on the object before setupNode is called, otherwise it never works! - /// - /// - internal virtual void PreSetupNode(params object[] ctorArgs) - { - //if people want to override then awesome but then we call setupNode so they need to ensure - // to call base.PreSetupNode - setupNode(); - } - - /// - /// Sets up the internal data of the CMSNode, used by the various constructors - /// - protected virtual void setupNode() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader(SqlSingle, - sqlHelper.CreateParameter("@id", this.Id))) - { - if (dr.Read()) - { - PopulateCMSNodeFromReader(dr); - } - else - { - throw new ArgumentException(string.Format("No node exists with id '{0}'", Id)); - } - } - } - - /// - /// Sets up the node for the content tree, this makes no database calls, just sets the underlying properties - /// - /// The unique ID. - /// Type of the node object. - /// The level. - /// The newParent id. - /// The user id. - /// The path. - /// The text. - /// The create date. - /// if set to true [has children]. - protected void SetupNodeForTree(Guid uniqueID, Guid nodeObjectType, int leve, int parentId, int userId, string path, string text, - DateTime createDate, bool hasChildren) - { - _uniqueID = uniqueID; - _nodeObjectType = nodeObjectType; - _level = leve; - _parentid = parentId; - _userId = userId; - _path = path; - _text = text; - _createDate = createDate; - HasChildren = hasChildren; - } - - /// - /// Updates the temp path for the content tree. - /// - /// The path. - protected void UpdateTempPathForTree(string Path) - { - this._path = Path; - } - - protected virtual XmlNode GetPreviewXml(XmlDocument xd, Guid version) - { - var xmlDoc = new XmlDocument(); - string xmlStr; - - using (var scope = Current.ScopeProvider.CreateScope()) - { - xmlStr = scope.Database.ExecuteScalar( - "select xml from cmsPreviewXml where nodeID = @nodeId and versionId = @versionId", - new { nodeId = Id, versionId = version }); - scope.Complete(); - } - - if (xmlStr.IsNullOrWhiteSpace()) return null; - - xmlDoc.LoadXml(xmlStr); - - return xd.ImportNode(xmlDoc.FirstChild, true); - } - - protected internal virtual bool PreviewExists(Guid versionId) - { - using (var scope = Current.ScopeProvider.CreateScope()) - { - var exists = scope.Database.ExecuteScalar( - "SELECT COUNT(nodeId) FROM cmsPreviewXml WHERE nodeId=@nodeId and versionId = @versionId", - new { nodeId = Id, versionId = versionId }) != 0; - scope.Complete(); - return exists; - } - } - - /// - /// This needs to be synchronized since we are doing multiple sql operations in one method - /// - /// - /// - [MethodImpl(MethodImplOptions.Synchronized)] - protected void SavePreviewXml(XmlNode x, Guid versionId) - { - var sql = PreviewExists(versionId) ? "UPDATE cmsPreviewXml SET xml = @xml, timestamp = @timestamp WHERE nodeId=@nodeId AND versionId = @versionId" - : "INSERT INTO cmsPreviewXml(nodeId, versionId, timestamp, xml) VALUES (@nodeId, @versionId, @timestamp, @xml)"; - - using (var scope = Current.ScopeProvider.CreateScope()) - { - scope.Database.Execute( - sql, new { nodeId = Id, versionId = versionId, timestamp = DateTime.Now, xml = x.OuterXml }); - scope.Complete(); - } - } - - protected void PopulateCMSNodeFromReader(IRecordsReader dr) - { - // testing purposes only > original umbraco data hasn't any unique values ;) - // And we need to have a newParent in order to create a new node .. - // Should automatically add an unique value if no exists (or throw a decent exception) - if (dr.IsNull("uniqueID")) _uniqueID = Guid.NewGuid(); - else _uniqueID = dr.GetGuid("uniqueID"); - - _nodeObjectType = dr.GetGuid("nodeObjectType"); - _level = dr.GetShort("level"); - _path = dr.GetString("path"); - _parentid = dr.GetInt("parentId"); - _text = dr.GetString("text"); - _sortOrder = dr.GetInt("sortOrder"); - _userId = dr.GetInt("nodeUser"); - _createDate = dr.GetDateTime("createDate"); - _isTrashed = dr.GetBoolean("trashed"); - } - - internal protected void PopulateCMSNodeFromUmbracoEntity(IUmbracoEntity content, Guid objectType) - { - _uniqueID = content.Key; - _nodeObjectType = objectType; - _level = content.Level; - _path = content.Path; - _parentid = content.ParentId; - _text = content.Name; - _sortOrder = content.SortOrder; - _userId = content.CreatorId; - _createDate = content.CreateDate; - _isTrashed = content.Trashed; - Entity = content; - } - - internal protected void PopulateCMSNodeFromUmbracoEntity(IAggregateRoot content, Guid objectType) - { - _uniqueID = content.Key; - _nodeObjectType = objectType; - _createDate = content.CreateDate; - } - - #endregion - - - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/CMSPreviewNode.cs b/src/umbraco.cms/businesslogic/CMSPreviewNode.cs deleted file mode 100644 index 002c1acfe5..0000000000 --- a/src/umbraco.cms/businesslogic/CMSPreviewNode.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Xml; -using umbraco.cms.businesslogic.web; -using umbraco.DataLayer; -using umbraco.BusinessLogic; -using System.IO; -using System.Text.RegularExpressions; -using System.ComponentModel; -using Umbraco.Core.IO; - -namespace umbraco.cms.businesslogic -{ - public class CMSPreviewNode - { - public int NodeId { get; set; } - public int Level { get; set; } - public Guid Version { get; set; } - public int ParentId { get; set; } - public int SortOrder { get; set; } - public string Xml { get; set; } - public bool IsDraft { get; set; } - - public CMSPreviewNode() - { - - } - - public CMSPreviewNode(int nodeId, Guid version, int parentId, int level, int sortOrder, string xml, bool isDraft) - { - NodeId = nodeId; - Version = version; - ParentId = parentId; - Level = level; - SortOrder = sortOrder; - Xml = xml; - IsDraft = isDraft; - } - } -} diff --git a/src/umbraco.cms/businesslogic/Content.cs b/src/umbraco.cms/businesslogic/Content.cs deleted file mode 100644 index 768243795d..0000000000 --- a/src/umbraco.cms/businesslogic/Content.cs +++ /dev/null @@ -1,365 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml; -using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.IO; -using Umbraco.Core.Models; -using Umbraco.Core.Models.EntityBase; -using umbraco.DataLayer; -using System.Runtime.CompilerServices; -using umbraco.BusinessLogic; -using Umbraco.Core.Composing; -using Umbraco.Core.Events; -using Umbraco.Core.Persistence; -using Umbraco.Core.Media; -using File = System.IO.File; - -using PropertyType = umbraco.cms.businesslogic.propertytype.PropertyType; - -namespace umbraco.cms.businesslogic -{ - /// - /// Content is an intermediate layer between CMSNode and class'es which will use generic data. - /// - /// Content is a datastructure that holds generic data defined in its corresponding ContentType. Content can in some - /// sence be compared to a row in a database table, it's contenttype hold a definition of the columns and the Content - /// contains the data - /// - /// Note that Content data in umbraco is *not* tablular but in a treestructure. - /// - /// - [Obsolete("Obsolete, Use Umbraco.Core.Models.Content or Umbraco.Core.Models.Media", false)] - public class Content : CMSNode - { - #region Private Members - - private Guid _version; - private DateTime _versionDate; - private XmlNode _xml; - private bool _versionDateInitialized; - private string _contentTypeIcon; - private ContentType _contentType; - protected internal IContentBase ContentBase; - - #endregion - - #region Constructors - - protected internal Content(int id, Guid version) - : base(id, new object[] { version }) - { - } - - public Content(int id) : base(id) { } - - protected Content(int id, bool noSetup) : base(id, noSetup) { } - - protected Content(Guid id) : base(id) { } - - protected Content(Guid id, bool noSetup) : base(id, noSetup) { } - - protected internal Content(IUmbracoEntity entity) : base(entity) { } - - protected internal Content(IContentBase contentBase) - : base(contentBase) - { - ContentBase = contentBase; - _version = ContentBase.Version; - _versionDate = ContentBase.UpdateDate; - _versionDateInitialized = true; - } - - #endregion - - #region Static Methods - - /// - /// Retrive a list of Content sharing the ContentType - /// - /// The ContentType - /// A list of Content objects sharing the ContentType defined. - [Obsolete("Obsolete, Use Umbraco.Core.Services.ContentService.GetContentOfContentType() or Umbraco.Core.Services.MediaService.GetMediaOfMediaType()", false)] - public static Content[] getContentOfContentType(ContentType ct) - { - var list = new List(); - var content = Current.Services.ContentService.GetContentOfContentType(ct.Id); - list.AddRange(content.OrderBy(x => x.Name).Select(x => new Content(x))); - - var media = Current.Services.MediaService.GetMediaOfMediaType(ct.Id); - list.AddRange(media.OrderBy(x => x.Name).Select(x => new Content(x))); - - return list.ToArray(); - } - - /// - /// Initialize a contentobject given a version. - /// - /// The version identifier - /// The Content object from the given version - [Obsolete("Obsolete, Use Umbraco.Core.Services.ContentService.GetByIdVersion() or Umbraco.Core.Services.MediaService.GetByIdVersion()", false)] - public static Content GetContentFromVersion(Guid version) - { - var content = Current.Services.ContentService.GetByVersion(version); - if (content != null) - { - return new Content(content); - } - - var media = Current.Services.MediaService.GetByVersion(version); - return new Content(media); - } - - #endregion - - #region Public Properties - - /// - /// Get the newParent id of the node - /// - public override int ParentId - { - get { return ContentBase == null ? base.ParentId : ContentBase.ParentId; } - } - - /// - /// The current Content objects ContentType, which defines the Properties of the Content (data) - /// - public ContentType ContentType - { - get - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - if (_contentType == null) - { - object o = sqlHelper.ExecuteScalar( - "Select ContentType from cmsContent where nodeId=@nodeid", - sqlHelper.CreateParameter("@nodeid", this.Id)); - if (o == null) - return null; - int contentTypeId; - if (int.TryParse(o.ToString(), out contentTypeId) == false) - return null; - - try - { - _contentType = new ContentType(contentTypeId); - } - catch - { - return null; - } - } - } - return _contentType; - } - set - { - _contentType = value; - } - } - - /// - /// The icon used in the tree - placed in this layer for performance reasons. - /// - /// - /// This is here for performance reasons only. If the _contentTypeIcon is manually set - /// then a database call is not made to initialize the ContentType. - /// - /// The data layer has slightly changed in 4.1 so that for Document and Media, the ContentType - /// is automatically initialized with one SQL call when creating the documents/medias so using this - /// method or the ContentType.IconUrl property when accessing the icon from Media or Document - /// won't affect performance. - /// - public string ContentTypeIcon - { - get - { - if (_contentTypeIcon == null && this.ContentType != null) - _contentTypeIcon = this.ContentType.IconUrl; - return _contentTypeIcon ?? string.Empty; - } - set - { - _contentTypeIcon = value; - } - } - - /// - /// The createtimestamp on this version - /// - public DateTime VersionDate - { - get - { - if (_versionDateInitialized) return _versionDate; - - // content & media have a version date in cmsContentVersion that is updated when saved - use it - using (var scope = Current.ScopeProvider.CreateScope()) - { - _versionDate = scope.Database.ExecuteScalar("SELECT versionDate FROM cmsContentVersion WHERE versionId=@versionId", - new { versionId = Version }); - scope.Complete(); - } - _versionDateInitialized = true; - return _versionDate; - } - set - { - _versionDate = value; - _versionDateInitialized = true; - } - } - - - /// - /// Content is under version control, you are able to programatically create new versions - /// - public Guid Version - { - get - { - if (_version == Guid.Empty) - { - string sql = "Select versionId from cmsContentVersion where contentID = " + this.Id + - " order by id desc "; - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader(sql)) - { - if (!dr.Read()) - _version = Guid.Empty; - else - _version = dr.GetGuid("versionId"); - } - } - return _version; - } - set { _version = value; } - } - - #endregion - - #region Public Methods - - /// - /// Used to persist object changes to the database. This ensures that the properties are re-loaded from the database. - /// - public override void Save() - { - base.Save(); - - } - - /// - - /// Deletes the current Content object, must be overridden in the child class. - /// - public override void delete() - { - - // Delete all data associated with this content - this.deleteAllProperties(); - - using (var scope = Current.ScopeProvider.CreateScope()) - { - OnDeletedContent(new ContentDeleteEventArgs(scope.Database, Id)); - scope.Complete(); - } - - // Delete version history - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Delete from cmsContentVersion where ContentId = " + this.Id); - - // Delete Contentspecific data () - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Delete from cmsContent where NodeId = " + this.Id); - - // Delete Nodeinformation!! - base.delete(); - } - - #endregion - - #region Protected Methods - - /// - /// This is purely for a hackity hack hack hack in order to make the new Document(id, version) constructor work because - /// the Version property needs to be set on the object before setupNode is called, otherwise it never works! - /// - /// - internal override void PreSetupNode(params object[] ctorArgs) - { - //we know that there is one ctor arg and it is a GUID since we are only calling the base - // ctor with this overload for one purpose. - var version = (Guid)ctorArgs[0]; - _version = version; - - base.PreSetupNode(ctorArgs); - } - - /// - /// Sets up the ContentType property for this content item and sets the addition content properties manually. - /// If the ContentType property is not already set, then this will get the ContentType from Cache. - /// - /// - /// - /// - /// - protected void InitializeContent(int InitContentType, Guid InitVersion, DateTime InitVersionDate, string InitContentTypeIcon) - { - - if (_contentType == null) - _contentType = ContentType.GetContentType(InitContentType); - - _version = InitVersion; - _versionDate = InitVersionDate; - _contentTypeIcon = InitContentTypeIcon; - } - - - - #endregion - - #region Private Methods - - - - /// - /// Optimized method for bulk deletion of properties´on a Content object. - /// - protected void deleteAllProperties() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Delete from cmsPropertyData where contentNodeId = @nodeId", sqlHelper.CreateParameter("@nodeId", this.Id)); - } - - #endregion - - #region Change Events - - // this is temp. until we get rid of Content - - internal protected class ContentDeleteEventArgs : EventArgs - { - public ContentDeleteEventArgs(IUmbracoDatabase database, int id) - { - Database = database; - Id = id; - } - - public int Id { get; private set; } - public IUmbracoDatabase Database { get; private set; } - } - - internal static event TypedEventHandler DeletedContent; - - internal protected void OnDeletedContent(ContentDeleteEventArgs args) - { - DeletedContent?.Invoke(this, args); - } - #endregion - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/ContentType.cs b/src/umbraco.cms/businesslogic/ContentType.cs deleted file mode 100644 index 80b217995b..0000000000 --- a/src/umbraco.cms/businesslogic/ContentType.cs +++ /dev/null @@ -1,1686 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; -using System.Runtime.CompilerServices; -using System.Linq; -using umbraco.BusinessLogic; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Models; -using Umbraco.Core.Models.Rdbms; -using umbraco.cms.businesslogic.propertytype; -using umbraco.cms.businesslogic.web; -using umbraco.DataLayer; -using Umbraco.Core.Composing; -using Language = umbraco.cms.businesslogic.language.Language; -using PropertyType = umbraco.cms.businesslogic.propertytype.PropertyType; - -namespace umbraco.cms.businesslogic -{ - /// - /// ContentTypes defines the datafields of Content objects of that type, it's similar to defining columns - /// in a database table, where the PropertyTypes on the ContentType each responds to a Column, and the Content - /// objects is similar to a row of data, where the Properties on the Content object corresponds to the PropertyTypes - /// on the ContentType. - /// - /// Besides data definition, the ContentType also defines the sorting and grouping (in tabs) of Properties/Datafields - /// on the Content and which Content (by ContentType) can be created as child to the Content of the ContentType. - /// - [Obsolete("Obsolete, Use Umbraco.Core.Models.ContentType or Umbraco.Core.Models.MediaType or or Umbraco.Core.Models.MemberType", false)] - public class ContentType : CMSNode - { - #region Constructors - - /// - /// - /// - /// - public ContentType(int id) : base(id) { } - - /// - /// Initializes a new instance of the class. - /// - /// The id. - public ContentType(Guid id) : base(id) { } - - public ContentType(int id, bool noSetup) : base(id, noSetup) { } - - public ContentType(Guid id, bool noSetup) : base(id, noSetup) { } - - /// - /// Creates a new content type object manually. - /// - /// - /// - /// - /// - /// - /// - /// - /// This is like creating a ContentType node using optimized mode but this lets you set - /// all of the properties that are initialized normally from the database. - /// This is used for performance reasons. - /// - internal ContentType(int id, string alias, string icon, string thumbnail, int? masterContentType, bool? isContainer) - : base(id, true) - { - _alias = alias; - _iconurl = icon; - _thumbnail = thumbnail; - - if (masterContentType.HasValue) - MasterContentType = masterContentType.Value; - - if (isContainer.HasValue) - _isContainerContentType = isContainer.Value; - } - - internal ContentType(IContentTypeComposition contentType) : base(contentType) - { - ContentTypeItem = contentType; - } - - #endregion - - #region Constants and static members - - protected internal const string m_SQLOptimizedGetAll = @" - SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text, - allowAtRoot, isContainer, Alias,icon,thumbnail,description - FROM umbracoNode INNER JOIN cmsContentType ON umbracoNode.id = cmsContentType.nodeId - WHERE nodeObjectType = @nodeObjectType"; - - #endregion - - #region Static Methods - - /// - /// Used for cache so we don't have to lookup column names all the time, this is actually only used for the ChildrenAsTable methods - /// - private static readonly ConcurrentDictionary> AliasToNames = new ConcurrentDictionary>(); - private static readonly ConcurrentDictionary, Guid> PropertyTypeCache = new ConcurrentDictionary, Guid>(); - - /// - /// Returns a content type's columns alias -> name mapping - /// - /// - /// - /// - /// This is currently only used for ChildrenAsTable methods, caching is moved here instead of in the app logic so we can clear the cache - /// - internal static IDictionary GetAliasesAndNames(string contentTypeAlias) - { - return AliasToNames.GetOrAdd(contentTypeAlias, s => - { - var ct = GetByAlias(contentTypeAlias); - var userFields = ct.PropertyTypes.ToDictionary(x => x.Alias, x => x.Name); - return userFields; - }); - } - - /// - /// Removes the static object cache - /// - /// - public static void RemoveFromDataTypeCache(string contentTypeAlias) - { - var toDelete = PropertyTypeCache.Keys.Where(key => string.Equals(key.Item1, contentTypeAlias)).ToList(); - foreach (var key in toDelete) - { - Guid id; - PropertyTypeCache.TryRemove(key, out id); - } - AliasToNames.Clear(); - } - - /// - /// Removes the static object cache - /// - internal static void RemoveAllDataTypeCache() - { - AliasToNames.Clear(); - PropertyTypeCache.Clear(); - } - - - - /// - /// Gets the type of the content. - /// - /// The id. - /// - public static ContentType GetContentType(int id) - { - return Current.ApplicationCache.RuntimeCache.GetCacheItem - (string.Format("{0}{1}", CacheKeys.ContentTypeCacheKey, id), - timeout: TimeSpan.FromMinutes(30), - getCacheItem: () => new ContentType(id)); - } - - // This is needed, because the Tab class is protected and as such it's not possible for - // the PropertyType class to easily access the cache flusher - /// - /// Flushes the tab cache. - /// - /// The tab id. - [Obsolete("There is no cache to flush for tabs")] - public static void FlushTabCache(int TabId, int ContentTypeId) - { - Tab.FlushCache(TabId, ContentTypeId); - } - - /// - /// Creates a new ContentType - /// - /// The CMSNode Id of the ContentType - /// The Alias of the ContentType - /// The Iconurl of Contents of this ContentType - protected static void Create(int NodeId, string Alias, string IconUrl) - { - Create(NodeId, Alias, IconUrl, true); - } - - internal static void Create(int nodeId, string alias, string iconUrl, bool formatAlias) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "Insert into cmsContentType (nodeId,alias,icon) values (" + - nodeId + ",'" + - (formatAlias ? alias.ToSafeAliasWithForcingCheck() : alias) + - "','" + iconUrl + "')"); - } - - /// - /// Initializes a ContentType object given the Alias. - /// - /// Alias of the content type - /// - /// The ContentType with the corrosponding Alias - /// - public static ContentType GetByAlias(string Alias) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return new ContentType(sqlHelper.ExecuteScalar("SELECT nodeid FROM cmsContentType WHERE alias = @alias", - sqlHelper.CreateParameter("@alias", Alias))); - } - - /// - /// Helper method for getting the Tab id from a given PropertyType - /// - /// The PropertyType from which to get the Tab Id - /// The Id of the Tab on which the PropertyType is placed - public static int getTabIdFromPropertyType(PropertyType pt) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - object tmp = sqlHelper.ExecuteScalar("Select propertyTypeGroupId from cmsPropertyType where id = " + pt.Id.ToString()); - if (tmp == DBNull.Value) - return 0; - return int.Parse(tmp.ToString()); - } - } - - #endregion - - #region Private Members - - private bool _allowAtRoot; - private string _alias; - private string _iconurl; - private string _description; - private string _thumbnail; - List m_masterContentTypes; - private bool _isContainerContentType; - private List _allowedChildContentTypeIDs; - private List _virtualTabs; - - protected internal IContentTypeComposition ContentTypeItem - { - get { return base.Entity as IContentTypeComposition; } - set { base.Entity = value; } - } - - #endregion - - #region Public Properties - - #region Regenerate Xml Structures - - - - /// - /// Returns all content ids associated with this content type - /// - /// - /// - /// This will generally just return the content ids associated with this content type but in the case - /// of a DocumentType where we can have inherited types, this will return all content Ids that are of - /// this content type or any descendant types as well. - /// - internal virtual IEnumerable GetContentIdsForContentType() - { - var ids = new List(); - //get all the content item ids of the current content type - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader(@"SELECT DISTINCT cmsContent.nodeId FROM cmsContent - INNER JOIN cmsContentType ON cmsContent.contentType = cmsContentType.nodeId - WHERE cmsContentType.nodeId = @nodeId", - sqlHelper.CreateParameter("@nodeId", this.Id))) - { - while (dr.Read()) - { - ids.Add(dr.GetInt("nodeId")); - } - } - return ids; - } - - - - /// - /// Clears all xml structures in the cmsContentXml table for the current content type - /// - internal virtual void ClearXmlStructuresForContent() - { - //Remove all items from the cmsContentXml table that are of this current content type - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery(@"DELETE FROM cmsContentXml WHERE nodeId IN - (SELECT DISTINCT cmsContent.nodeId FROM cmsContent - INNER JOIN cmsContentType ON cmsContent.contentType = cmsContentType.nodeId - WHERE cmsContentType.nodeId = @nodeId)", - sqlHelper.CreateParameter("@nodeId", this.Id)); - } - - #endregion - - /// - /// The Alias of the ContentType, is used for import/export and more human readable initialization see: GetByAlias - /// method. - /// - public string Alias - { - get { return _alias; } - set - { - _alias = value.ToSafeAliasWithForcingCheck(); - - // validate if alias is empty - if (String.IsNullOrEmpty(_alias)) - { - throw new ArgumentOutOfRangeException("An Alias cannot be empty"); - } - - //This switches between using new vs. legacy api. - //Note that this is currently only done to support both DocumentType and MediaType, which use the new api and MemberType that doesn't. - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update cmsContentType set alias = @alias where nodeId = @id", - sqlHelper.CreateParameter("@alias", _alias), - sqlHelper.CreateParameter("@id", Id)); - } - else - { - ContentTypeItem.Alias = _alias; - } - - // Remove from cache - FlushFromCache(Id); - } - } - - /// - /// A Content object is often (always) represented in the treeview in the Umbraco console, the ContentType defines - /// which Icon the Content of this type is representated with. - /// - public string IconUrl - { - get { return _iconurl; } - set - { - _iconurl = value; - - //This switches between using new vs. legacy api. - //Note that this is currently only done to support both DocumentType and MediaType, which use the new api and MemberType that doesn't. - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update cmsContentType set icon='" + value + "' where nodeid = " + Id); - } - else - { - ContentTypeItem.Icon = _iconurl; - } - - // Remove from cache - FlushFromCache(Id); - } - } - - /// - /// Get or Sets the Container status of the Content Type. A Container Content Type doesn't show its children in the tree, - /// but instead adds a tab when edited showing its children in a grid - /// - public bool IsContainerContentType - { - get { return _isContainerContentType; } - set - { - _isContainerContentType = value; - - //This switches between using new vs. legacy api. - //Note that this is currently only done to support both DocumentType and MediaType, which use the new api and MemberType that doesn't. - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "update cmsContentType set isContainer = @isContainer where nodeId = @id", - sqlHelper.CreateParameter("@isContainer", value), - sqlHelper.CreateParameter("@id", Id)); - } - else - { - ContentTypeItem.IsContainer = _isContainerContentType; - } - } - } - - /// - /// Gets or sets the 'allow at root' boolean - /// - public bool AllowAtRoot - { - get { return _allowAtRoot; } - set - { - _allowAtRoot = value; - - //This switches between using new vs. legacy api. - //Note that this is currently only done to support both DocumentType and MediaType, which use the new api and MemberType that doesn't. - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "update cmsContentType set allowAtRoot = @allowAtRoot where nodeId = @id", - sqlHelper.CreateParameter("@allowAtRoot", value), - sqlHelper.CreateParameter("@id", Id)); - } - else - { - ContentTypeItem.AllowedAsRoot = _allowAtRoot; - } - } - } - - /// - /// Gets or sets the description. - /// - /// The description. - public string Description - { - get - { - if (_description != null) - { - if (!_description.StartsWith("#")) - return _description; - var lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); - if (lang != null) - { - if (Current.Services.LocalizationService.DictionaryItemExists(_description.Substring(1, _description.Length - 1))) - { - var di = Current.Services.LocalizationService.GetDictionaryItemByKey(_description.Substring(1, _description.Length - 1)); - return di.GetTranslatedValue(lang.id); - } - } - - return "[" + _description + "]"; - } - - return _description; - } - set - { - _description = value; - - //This switches between using new vs. legacy api. - //Note that this is currently only done to support both DocumentType and MediaType, which use the new api and MemberType that doesn't. - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "update cmsContentType set description = @description where nodeId = @id", - sqlHelper.CreateParameter("@description", value), - sqlHelper.CreateParameter("@id", Id)); - } - else - { - ContentTypeItem.Description = _description; - } - - FlushFromCache(Id); - } - } - - /// - /// Gets or sets the thumbnail. - /// - /// The thumbnail. - public string Thumbnail - { - get { return _thumbnail; } - set - { - _thumbnail = value; - - //This switches between using new vs. legacy api. - //Note that this is currently only done to support both DocumentType and MediaType, which use the new api and MemberType that doesn't. - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "update cmsContentType set thumbnail = @thumbnail where nodeId = @id", - sqlHelper.CreateParameter("@thumbnail", value), - sqlHelper.CreateParameter("@id", Id)); - } - else - { - ContentTypeItem.Thumbnail = _thumbnail; - } - - FlushFromCache(Id); - } - } - - - /// - /// Human readable name/label - /// - /// - public override string Text - { - get - { - var tempText = base.Text; - if (!tempText.StartsWith("#")) - return tempText; - var lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); - if (lang != null) - { - - if (Current.Services.LocalizationService.DictionaryItemExists(tempText.Substring(1, tempText.Length - 1))) - { - var di = Current.Services.LocalizationService.GetDictionaryItemByKey(tempText.Substring(1, tempText.Length - 1)); - return di.GetTranslatedValue(lang.id); - } - } - - return "[" + tempText + "]"; - } - set - { - base.Text = value; - - if (ContentTypeItem != null) - { - ContentTypeItem.Name = value; - } - - // Remove from cache - FlushFromCache(Id); - } - } - - //THIS SHOULD BE IENUMERABLE NOT LIST! - - /// - /// The "datafield/column" definitions, a Content object of this type will have an equivalent - /// list of Properties. - /// - /// - /// Property types are are cached so any calls to this property will returne cached versions - /// - public List PropertyTypes - { - get - { - var cacheKey = GetPropertiesCacheKey(); - - return Current.ApplicationCache.RuntimeCache.GetCacheItem>( - cacheKey, - timeout: TimeSpan.FromMinutes(15), - getCacheItem: () => - { - //MCH NOTE: For the timing being I have changed this to a dictionary to ensure that property types - //aren't added multiple times through the MasterContentType structure, because each level loads - //its own + inherited property types, which is wrong. Once we are able to fully switch to the new api - //this should no longer be a problem as the composition always contains a correct list of property types. - var result = new Dictionary(); - - List ids; - using (var scope = Current.ScopeProvider.CreateScope()) - { - ids = scope.Database.Fetch( - "select id from cmsPropertyType where contentTypeId = @ctId order by sortOrder", - new { ctId = Id }); - scope.Complete(); - } - - foreach (var id in ids) - { - var pt = PropertyType.GetPropertyType(id); - if (pt != null) - result.Add(pt.Id, pt); - } - - // Get Property Types from the master content type - if (MasterContentTypes.Count > 0) - { - foreach (var mct in MasterContentTypes) - { - var pts = GetContentType(mct).PropertyTypes; - foreach (var pt in pts) - { - if (result.ContainsKey(pt.Id) == false) - result.Add(pt.Id, pt); - } - } - } - return result.Select(x => x.Value).ToList(); - }); - } - } - - public List MasterContentTypes - { - get - { - if (m_masterContentTypes == null) - { - // fixme - oops, what's this? - //var ct = Current.Services.ContentTypeService.GetContentType(Id); - //m_masterContentTypes = ct.CompositionPropertyGroups.Select(x => x.Id).ToList(); - - // back to normal - m_masterContentTypes = ContentTypeItem == null - ? new List() - : ContentTypeItem.CompositionIds().ToList(); - - if (ContentTypeItem == null) - { - //TODO Make this recursive, so it looks up Masters of the Master ContentType - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader( - @"SELECT parentContentTypeId FROM cmsContentType2ContentType WHERE childContentTypeId = @id", - sqlHelper.CreateParameter("@id", Id))) - { - while (dr.Read()) - { - m_masterContentTypes.Add(dr.GetInt("parentContentTypeId")); - } - } - } - - } - return m_masterContentTypes; - } - } - - /// - /// Gets or sets the Master Content Type for inheritance of tabs and properties. - /// - /// The ID of the Master Content Type - public int MasterContentType - { - get - { - if (ContentTypeItem == null) - return 0; - - return ContentTypeItem.ParentId == -1 ? 0 : ContentTypeItem.ParentId; - } - set - { - if (value != MasterContentType) - { - - if (ContentTypeItem == null) - { - //Legacy - if (MasterContentTypes.Count > 0) - { - var masterId = MasterContentTypes[0]; - RemoveParentContentType(masterId); - } - - AddParentContentType(value); - } - else - { - ContentTypeItem.ParentId = value; - - //Try to load the ContentType/MediaType through the new public api - if (nodeObjectType == new Guid(Constants.ObjectTypes.DocumentType)) - { - - } - - var newMaster = CallGetContentTypeMethod(value); - var added = ContentTypeItem.AddContentType(newMaster); - } - } - } - } - - public void AddParentContentType(int parentContentTypeId) - { - if (MasterContentTypes.Contains(parentContentTypeId)) - { - // Should we throw an exception if you try to add something that already exist? - } - else - { - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "INSERT INTO [cmsContentType2ContentType] (parentContentTypeId, childContentTypeId) VALUES (@parentContentTypeId, @childContentTypeId)", - sqlHelper.CreateParameter("@parentContentTypeId", parentContentTypeId), - sqlHelper.CreateParameter("@childContentTypeId", Id)); - - MasterContentTypes.Add(parentContentTypeId); - } - else - { - var newMaster = CallGetContentTypeMethod(parentContentTypeId); - var added = ContentTypeItem.AddContentType(newMaster); - } - } - } - - public bool IsMaster() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - return sqlHelper.ExecuteScalar("select count(*) from cmsContentType2ContentType where parentContentTypeId = @parentContentTypeId", - sqlHelper.CreateParameter("@parentContentTypeId", this.Id)) > 0; - } - - public IEnumerable GetChildTypes() - { - var cts = new List(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader(@"SELECT childContentTypeId FROM cmsContentType2ContentType WHERE parentContentTypeId = @parentContentTypeId", - sqlHelper.CreateParameter("@parentContentTypeId", Id))) - { - while (dr.Read()) - { - cts.Add(GetContentType(dr.GetInt("childContentTypeId"))); - } - } - - return cts; - } - - public void RemoveParentContentType(int parentContentTypeId) - { - if (MasterContentTypes.Contains(parentContentTypeId) == false) - { - // Should we throw an exception if you're trying to remove something that doesn't exist? - } - else - { - - // Clean up property data (when we remove a reference we also need to remove all data relating to the doc type! - // So that would be all propertyData that uses a propertyType from the content type with 'parentContentTypeId' and - // has a nodetype of this id - var contentTypeToRemove = new ContentType(parentContentTypeId); - - RemoveMasterPropertyTypeData(contentTypeToRemove, this); - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "DELETE FROM [cmsContentType2ContentType] WHERE parentContentTypeId = @parentContentTypeId AND childContentTypeId = @childContentTypeId", - sqlHelper.CreateParameter("@parentContentTypeId", parentContentTypeId), - sqlHelper.CreateParameter("@childContentTypeId", Id)); - MasterContentTypes.Remove(parentContentTypeId); - } - } - - private void RemoveMasterPropertyTypeData(ContentType contentTypeToRemove, ContentType currentContentType) - { - foreach (var pt in contentTypeToRemove.PropertyTypes) - { - if (pt.ContentTypeId == contentTypeToRemove.Id) - { - // before we can remove a parent content type we need to remove all data that - // relates to property types - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - @"delete cmsPropertyData from cmsPropertyData - inner join cmsContent on cmsContent.nodeId = cmsPropertyData.contentNodeId - where cmsPropertyData.propertyTypeId = @propertyType - and contentType = @contentType", - sqlHelper.CreateParameter("@contentType", currentContentType.Id), - sqlHelper.CreateParameter("@propertyType", pt.Id)); - } - } - - // remove sub data too - foreach (var ct in currentContentType.GetChildTypes()) - RemoveMasterPropertyTypeData(contentTypeToRemove, ct); - } - - public IEnumerable PropertyTypeGroups - { - get { return PropertyTypeGroup.GetPropertyTypeGroupsFromContentType(Id); } - } - - /// - /// Retrieve a list of all Tabs on the current ContentType - /// - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public TabI[] getVirtualTabs - { - get - { - EnsureVirtualTabs(); - return _virtualTabs.ToArray(); - } - } - - - /// - /// Clears the locally loaded tabs which forces them to be reloaded next time they requested - /// - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public void ClearVirtualTabs() - { - //NOTE: SD: There is no cache to clear so this doesn't actually do anything - //NOTE: SD: There is no cache to clear so this doesn't actually do anything - foreach (var t in getVirtualTabs) - Tab.FlushCache(t.Id, Id); - - _virtualTabs = null; - } - - /// - /// The list of ContentType Id's that defines which Content (by ContentType) can be created as child - /// to the Content of this ContentType - /// - public int[] AllowedChildContentTypeIDs - { - get - { - //optimize this property so it lazy loads the data only one time. - if (_allowedChildContentTypeIDs == null) - { - _allowedChildContentTypeIDs = new List(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader("Select AllowedId from cmsContentTypeAllowedContentType where id=" + Id)) - { - while (dr.Read()) - { - _allowedChildContentTypeIDs.Add(dr.GetInt("AllowedId")); - } - } - } - - return _allowedChildContentTypeIDs.ToArray(); - } - set - { - _allowedChildContentTypeIDs = value.ToList(); - - //This switches between using new vs. legacy api. - //Note that this is currently only done to support both DocumentType and MediaType, which use the new api and MemberType that doesn't. - if (ContentTypeItem == null) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "delete from cmsContentTypeAllowedContentType where id=" + Id); - foreach (int i in value) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "insert into cmsContentTypeAllowedContentType (id,AllowedId) values (" + - Id + "," + i + ")"); - } - } - else - { - var list = new List(); - int sort = 0; - foreach (var i in value) - { - int id = i; - list.Add(new ContentTypeSort(id, sort)); - sort++; - } - - ContentTypeItem.AllowedContentTypes = list; - } - } - } - - #endregion - - #region Public Methods - /// - /// Gets the raw text. - /// - /// - public string GetRawText() - { - return base.Text; - } - public string GetRawDescription() - { - return _description; - } - - /// - /// Retrieve a list of all ContentTypes - /// - /// The list of all ContentTypes - public ContentType[] GetAll() - { - var contentTypes = new List(); - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader(m_SQLOptimizedGetAll.Trim(), sqlHelper.CreateParameter("@nodeObjectType", nodeObjectType))) - { - while (dr.Read()) - { - //create the ContentType object without setting up - var ct = new ContentType(dr.Get("id"), true); - //populate it's CMSNode properties - ct.PopulateCMSNodeFromReader(dr); - //populate it's ContentType properties - ct.PopulateContentTypeNodeFromReader(dr); - - contentTypes.Add(ct); - } - } - - return contentTypes.ToArray(); - - } - - - /// - /// Adding a PropertyType to a Tab, the Tabs are primarily used for making the - /// editing interface more userfriendly. - /// - /// The PropertyType - /// The Id of the Tab - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public void SetTabOnPropertyType(PropertyType pt, int TabId) - { - // This is essentially just a wrapper for the property - pt.TabId = TabId; - //flush the content type cache, the the tab cache (why so much cache?! argh!) - pt.FlushCacheBasedOnTab(); - } - - /// - /// Removing a PropertyType from the associated Tab - /// - /// The PropertyType which should be freed from its tab - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public void removePropertyTypeFromTab(PropertyType pt) - { - pt.TabId = 0; //this will set to null in the database. - - if (ContentTypeItem != null) - { - ContentTypeItem.RemovePropertyType(pt.Alias); - } - - // Remove from cache - FlushFromCache(Id); - } - - /// - /// Creates a new Tab on the Content - /// - /// Returns the Id of the new Tab - /// - [MethodImpl(MethodImplOptions.Synchronized)] - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public int AddVirtualTab(string Caption) - { - // The method is synchronized - PropertyTypeGroup ptg = new PropertyTypeGroup(Id, Caption); - ptg.Save(); - - // Remove from cache - FlushFromCache(Id); - - return ptg.Id; - } - - /// - /// Releases all PropertyTypes on tab (this does not delete the PropertyTypes) and then Deletes the Tab - /// - /// The Id of the Tab to be deleted. - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public void DeleteVirtualTab(int id) - { - PropertyTypeGroup.GetPropertyTypeGroup(id).Delete(); - - // Remove from cache - FlushFromCache(Id); - } - - /// - /// Updates the caption of the Tab - /// - /// The Id of the Tab to be updated - /// The new Caption - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public void SetTabName(int tabId, string Caption) - { - var ptg = PropertyTypeGroup.GetPropertyTypeGroup(tabId); - ptg.Name = Caption; - ptg.Save(); - - // Remove from cache - FlushFromCache(Id); - } - - /// - /// Updates the sort order of the Tab - /// - /// The Id of the Tab to be updated - /// The new order number - [Obsolete("Use PropertyTypeGroup methods instead", false)] - public void SetTabSortOrder(int tabId, int sortOrder) - { - var ptg = PropertyTypeGroup.GetPropertyTypeGroup(tabId); - ptg.SortOrder = sortOrder; - ptg.Save(); - - // Remove from cache - FlushFromCache(Id); - } - - /// - /// Retrieve a PropertyType by it's alias - /// - /// PropertyType alias - /// The PropertyType with the given Alias - public PropertyType getPropertyType(string alias) - { - // NH 22-08-08, Get from the property type stack to ensure support of master document types - object o = PropertyTypes.Find(pt => pt.Alias == alias); - - if (o == null) - { - return null; - } - return (PropertyType)o; - } - /// - /// Deletes the current ContentType - /// - public override void delete() - { - // Remove from cache - FlushFromCache(Id); - - // Delete all propertyTypes - foreach (var pt in PropertyTypes) - { - if (pt.ContentTypeId == Id) - { - pt.delete(); - } - } - - // delete all tabs - foreach (PropertyTypeGroup ptg in PropertyTypeGroups) - { - if (ptg.ContentTypeId == this.Id) - { - ptg.Delete(); - } - } - - //need to delete the allowed relationships between content types - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("delete from cmsContentTypeAllowedContentType where AllowedId=@allowedId or Id=@id", - sqlHelper.CreateParameter("@allowedId", Id), - sqlHelper.CreateParameter("@id", Id)); - - // delete contenttype entrance - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Delete from cmsContentType where NodeId = " + Id); - - // delete CMSNode entrance - base.delete(); - } - - #endregion - - #region Protected Methods - - internal protected void PopulateContentTypeFromContentTypeBase(IContentTypeComposition contentType) - { - _alias = contentType.Alias; - _iconurl = contentType.Icon; - _isContainerContentType = contentType.IsContainer; - _allowAtRoot = contentType.AllowedAsRoot; - _thumbnail = contentType.Thumbnail; - _description = contentType.Description; - - /*if (ContentTypeItem == null) - ContentTypeItem = contentType;*/ - } - - protected void PopulateContentTypeNodeFromReader(IRecordsReader dr) - { - _alias = dr.GetString("Alias"); - _iconurl = dr.GetString("icon"); - _isContainerContentType = dr.GetBoolean("isContainer"); - _allowAtRoot = dr.GetBoolean("allowAtRoot"); - - if (!dr.IsNull("thumbnail")) - _thumbnail = dr.GetString("thumbnail"); - if (!dr.IsNull("description")) - _description = dr.GetString("description"); - } - - /// - /// Set up the internal data of the ContentType - /// - protected override void setupNode() - { - base.setupNode(); - - //Try to load the ContentType/MediaType through the new public api - if (nodeObjectType == new Guid(Constants.ObjectTypes.DocumentType)) - { - var contentType = CallGetContentTypeMethod(Id); - if (contentType != null) - { - PopulateContentTypeFromContentTypeBase(contentType); - return; - } - } - else if (nodeObjectType == new Guid(Constants.ObjectTypes.MediaType)) - { - var mediaType = CallGetContentTypeMethod(Id); - if (mediaType != null) - { - PopulateContentTypeFromContentTypeBase(mediaType); - return; - } - } - else if (nodeObjectType == new Guid(Constants.ObjectTypes.MemberType)) - { - var memberType = CallGetContentTypeMethod(Id); - if (memberType != null) - { - PopulateContentTypeFromContentTypeBase(memberType); - return; - } - } - - // TODO: Load master content types - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader("Select allowAtRoot, isContainer, Alias,icon,thumbnail,description from cmsContentType where nodeid=" + Id) - ) - { - if (dr.Read()) - { - PopulateContentTypeNodeFromReader(dr); - } - else - { - throw new ArgumentException("No Contenttype with id: " + Id); - } - } - } - - /// - /// Flushes the cache. - /// - /// The id. - public static void FlushFromCache(int id) - { - - var ct = new ContentType(id); - Current.ApplicationCache.RuntimeCache.ClearCacheItem(string.Format("{0}{1}", CacheKeys.ContentTypeCacheKey, id)); - Current.ApplicationCache.RuntimeCache.ClearCacheItem(ct.GetPropertiesCacheKey()); - ct.ClearVirtualTabs(); - - //clear the content type from the property datatype cache used by razor - RemoveFromDataTypeCache(ct.Alias); - - // clear anything that uses this as master content type - if (ct.nodeObjectType == DocumentType._objectType - || ct.nodeObjectType == media.MediaType._objectType) - { - //NOTE Changed from "DocumentType.GetAllAsList().FindAll(dt => dt.MasterContentType == id)" to loading master contenttypes directly from the db. - //Related to http://issues.umbraco.org/issue/U4-1714 - IList dtos; - using (var scope = Current.ScopeProvider.CreateScope()) - { - dtos = scope.Database.Fetch("WHERE parentContentTypeId = @Id", new { Id = id }); - } - foreach (var dto in dtos) - { - FlushFromCache(dto.ChildId); - } - } - } - - [Obsolete("The content type cache is automatically cleared by Umbraco when a content type is saved, this method is no longer used")] - protected internal void FlushAllFromCache() - { - Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.ContentTypeCacheKey); - Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.ContentTypePropertiesCacheKey); - - RemoveAllDataTypeCache(); - ClearVirtualTabs(); - } - - #endregion - - #region Private Methods - - private Func CallGetContentTypeMethod - { - get - { - if (nodeObjectType == new Guid(Constants.ObjectTypes.DocumentType)) - { - return Current.Services.ContentTypeService.Get; - } - if (nodeObjectType == new Guid(Constants.ObjectTypes.MediaType)) - { - return Current.Services.MediaTypeService.Get; - } - if (nodeObjectType == new Guid(Constants.ObjectTypes.MemberType)) - { - return Current.Services.MemberTypeService.Get; - } - - //default to content - // should throw! - return Current.Services.ContentTypeService.Get; - } - } - - /// - /// The cache key used to cache the properties for the content type - /// - /// - private string GetPropertiesCacheKey() - { - return CacheKeys.ContentTypePropertiesCacheKey + this.Id; - } - - - private readonly object _virtualTabLoadLock = new object(); - /// - /// Checks if we've loaded the virtual tabs into memory and if not gets them from the databse. - /// - [Obsolete("Use PropertyTypeGroup methods instead", false)] - private void EnsureVirtualTabs() - { - // This class can be cached and potentially shared between multiple threads. - // Two or more threads can attempt to lazyily-load its virtual tabs at the same time. - // If that happens, the m_VirtualTabs will contain duplicates. - // We must prevent two threads from running InitializeVirtualTabs at the same time. - // We must also prevent m_VirtualTabs from being modified while it is being populated. - if (_virtualTabs == null || _virtualTabs.Count == 0) - { - lock (_virtualTabLoadLock) - { - //optimize, lazy load the data only one time - if (_virtualTabs == null || _virtualTabs.Count == 0) - { - InitializeVirtualTabs(); - } - } - } - } - - - /// - /// Loads the tabs into memory from the database and stores them in a local list for retreival - /// - [Obsolete("Use PropertyTypeGroup methods instead", false)] - private void InitializeVirtualTabs() - { - // somewhat fixing... this whole class should be removed anyways - var ct = ContentTypeItem ?? CallGetContentTypeMethod(Id); - - var tmp1 = ct.PropertyGroups - .Select(x => (TabI) new Tab(x.Id, x.Name, x.SortOrder, this)) - .Union(ct.ContentTypeComposition.SelectMany(x => GetContentType(x.Id).getVirtualTabs)) - .OrderBy(x => x.SortOrder) - .DistinctBy(x => x.Id) - .ToList(); - _virtualTabs = tmp1; - - /* - // While we are initialising, we should not use the class-scoped list, as it may be used by other threads - var temporaryList = new List(); - foreach (PropertyTypeGroup ptg in PropertyTypeGroups.Where(x => x.ParentId == 0 && x.ContentTypeId == this.Id)) - temporaryList.Add(new Tab(ptg.Id, ptg.Name, ptg.SortOrder, this)); - - // Master Content Type - if (MasterContentTypes.Count > 0) - { - foreach (var mct in MasterContentTypes) - temporaryList.AddRange(GetContentType(mct).getVirtualTabs.ToList()); - } - - - // sort all tabs - temporaryList.Sort((a, b) => a.SortOrder.CompareTo(b.SortOrder)); - - // now that we aren't going to modify the list, we can set it to the class-scoped variable. - _virtualTabs = temporaryList.DistinctBy(x => x.Id).ToList(); - */ - } - - #endregion - - #region Public TabI Interface - /// - /// An interface for the tabs, should be refactored - /// - public interface TabI - { - /// - /// Public identifier - /// - int Id { get; } - - /// - /// The text on the tab - /// - string Caption { get; } - - /// - /// The sortorder of the tab - /// - int SortOrder { get; } - - // zb-00036 #29889 : removed PropertyTypes property (not making sense), replaced with methods - - /// - /// Gets a list of all PropertyTypes on the Tab for a given ContentType. - /// - /// This includes properties inherited from master content types. - /// The unique identifier of the ContentType. - /// An array of PropertyType. - PropertyType[] GetPropertyTypes(int contentTypeId); - - [Obsolete("Please use GetPropertyTypes() instead", false)] - PropertyType[] PropertyTypes { get; } - - /// - /// Gets a list of all PropertyTypes on the Tab for a given ContentType. - /// - /// The unique identifier of the ContentType. - /// Indicates whether properties inherited from master content types should be included. - /// An array of PropertyType. - PropertyType[] GetPropertyTypes(int contentTypeId, bool includeInheritedProperties); - - /// - /// Gets a list if all PropertyTypes on the Tab for all ContentTypes. - /// - /// An IEnumerable of all the PropertyTypes. - List GetAllPropertyTypes(); - - /// - /// The contenttype - /// - int ContentType { get; } - - /// - /// Method for moving the tab up - /// - void MoveUp(); - - /// - /// Method for moving the tab down - /// - void MoveDown(); - } - #endregion - - #region Protected Tab Class - /// - /// A tab is merely a way to organize data on a ContentType to make it more - /// human friendly - /// - [Obsolete("Please use PropertyTypes instead", false)] - public class Tab : TabI - { - private readonly ContentType _contenttype; - - /// - /// Initializes a new instance of the class. - /// - /// The id. - /// The caption. - /// The sort order. - /// Type of the c. - public Tab(int id, string caption, int sortOrder, ContentType cType) - { - _id = id; - _caption = caption; - _sortOrder = sortOrder; - _contenttype = cType; - } - - public static Tab GetTab(int id) - { - Tab tab = null; - // Tabs have been replaced with PropertyTypeGroups, so we use the new api to provide legacy support - PropertyTypeGroup ptg = PropertyTypeGroup.GetPropertyTypeGroup(id); - if (ptg != null) - { - tab = new Tab(id, ptg.Name, ptg.SortOrder, new ContentType(ptg.ContentTypeId)); - } - - return tab; - } - - // zb-00036 #29889 : Fix content tab properties. - public PropertyType[] GetPropertyTypes(int contentTypeId) - { - return GetPropertyTypes(contentTypeId, true); - } - - // zb-00036 #29889 : Fix content tab properties. Replaces getPropertyTypes, which was - // loading all properties for the tab, causing exceptions here and there... we want - // the properties for the tab for a given content type, and we want them in the right order. - // Also this is public now because we removed the PropertyTypes property (not making sense). - public PropertyType[] GetPropertyTypes(int contentTypeId, bool includeInheritedProperties) - { - // NH, temp fix for 4.9 to use the new PropertyTypeGroup API - var pts = PropertyTypeGroup.GetPropertyTypeGroup(this.Id).GetPropertyTypes(); - - if (includeInheritedProperties) - { - // we need to - var contentType = businesslogic.ContentType.GetContentType(contentTypeId); - return pts.Where(x => contentType.MasterContentTypes.Contains(x.ContentTypeId) || x.ContentTypeId == contentTypeId).ToArray(); - } - - return pts.Where(x => x.ContentTypeId == contentTypeId).ToArray(); - } - - // zb-00036 #29889 : yet we may want to be able to get *all* property types - // Note: This will get ALL PropertyTypes that is associated with a specific Tab - // regardless of the PropertyTypes belonging to the current ContentType. - public List GetAllPropertyTypes() - { - var ct = _contenttype.ContentTypeItem ?? _contenttype.CallGetContentTypeMethod(_contenttype.Id); - return ct.CompositionPropertyTypes - .OrderBy(x => x.SortOrder) - .Select(x => x.Id) - .Select(PropertyType.GetPropertyType) - .ToList(); - - /* - var db = ApplicationContext.Current.DatabaseContext.Database; - var propertyTypeDtos = db.Fetch("WHERE propertyTypeGroupId = @Id", new { Id = _id }); - var tmp = propertyTypeDtos - .Select(propertyTypeDto => PropertyType.GetPropertyType(propertyTypeDto.Id)) - .ToList(); - - var propertyTypeGroupDtos = db.Fetch("WHERE parentGroupId = @Id", new { Id = _id }); - foreach (var propertyTypeGroupDto in propertyTypeGroupDtos) - { - var inheritedPropertyTypeDtos = db.Fetch("WHERE propertyTypeGroupId = @Id", new { Id = propertyTypeGroupDto.Id }); - tmp.AddRange(inheritedPropertyTypeDtos - .Select(propertyTypeDto => PropertyType.GetPropertyType(propertyTypeDto.Id)) - .ToList()); - } - - return tmp; - */ - } - - /// - /// A list of PropertyTypes on the Tab - /// - [Obsolete("Please use GetPropertyTypes() instead", false)] - public PropertyType[] PropertyTypes - { - get { return GetPropertyTypes(ContentType, true); } - } - - - - /// - /// Flushes the cache. - /// - /// The id. - /// - [Obsolete("There is no cache to flush for tabs")] - public static void FlushCache(int id, int contentTypeId) - { - //at some stage there was probably caching for tabs but this hasn't been in place for some time, so this method - //now does nothing. - } - - /// - /// Deletes this instance. - /// - public void Delete() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update cmsPropertyType set propertyTypeGroupId = NULL where propertyTypeGroupId = @id", - sqlHelper.CreateParameter("@id", Id)); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("delete from cmsPropertyTypeGroup where id = @id", - sqlHelper.CreateParameter("@id", Id)); - } - - /// - /// Gets the tab caption by id. - /// - /// The id. - /// - public static string GetCaptionById(int id) - { - try - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - var tempCaption = sqlHelper.ExecuteScalar("Select text from cmsPropertyTypeGroup where id = " + id.ToString()); - if (!tempCaption.StartsWith("#")) - return tempCaption; - var lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); - if (lang != null) - { - if (Current.Services.LocalizationService.DictionaryItemExists(tempCaption.Substring(1, tempCaption.Length - 1))) - { - var di = Current.Services.LocalizationService.GetDictionaryItemByKey(tempCaption.Substring(1, tempCaption.Length - 1)); - return di.GetTranslatedValue(lang.id); - } - } - return "[" + tempCaption + "]"; - } - } - catch - { - return null; - } - } - - /// - /// Gets the tab caption by id. - /// - /// The id. - /// - internal static string GetRawCaptionById(int id) - { - try - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - var tempCaption = sqlHelper.ExecuteScalar("Select text from cmsPropertyTypeGroup where id = " + id); - return tempCaption; - } - } - catch - { - return null; - } - } - - private readonly int _id; - - private int? _sortOrder; - - /// - /// The sortorder of the tab - /// - /// - public int SortOrder - { - get - { - if (!_sortOrder.HasValue) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - _sortOrder = sqlHelper.ExecuteScalar("select sortOrder from cmsPropertyTypeGroup where id = " + _id); - } - return _sortOrder.Value; - } - set - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("update cmsPropertyTypeGroup set sortOrder = " + value + " where id =" + _id); - } - } - - /// - /// Moves the Tab up - /// - [Obsolete("Please use GetPropertyTypes() instead", false)] - public void MoveUp() - { - FixTabOrder(); - // If this tab is not the first we can switch places with the previous tab - // hence moving it up. - if (SortOrder > 0) - { - var newsortorder = SortOrder - 1; - // Find the tab to switch with - var tabs = _contenttype.getVirtualTabs; - foreach (Tab t in tabs) - { - if (t.SortOrder == newsortorder) - t.SortOrder = SortOrder; - } - SortOrder = newsortorder; - } - } - - /// - /// Moves the Tab down - /// - [Obsolete("Please use GetPropertyTypes() instead", false)] - public void MoveDown() - { - FixTabOrder(); - // If this tab is not the last tab we can switch places with the next tab - // hence moving it down. - var tabs = _contenttype.getVirtualTabs; - if (SortOrder < tabs.Length - 1) - { - var newsortorder = SortOrder + 1; - // Find the tab to switch with - foreach (Tab t in tabs) - { - if (t.SortOrder == newsortorder) - t.SortOrder = SortOrder; - } - SortOrder = newsortorder; - } - } - - /// - /// Method for retrieving the original, non processed name from the db - /// - /// - /// The original, non processed name from the db - /// - public string GetRawCaption() - { - return _caption; - } - - - /// - /// Fixes the tab order. - /// - private void FixTabOrder() - { - var tabs = _contenttype.getVirtualTabs; - for (int i = 0; i < tabs.Length; i++) - { - var t = (Tab)tabs[i]; - t.SortOrder = i; - } - } - - - /// - /// Public identifier - /// - /// - public int Id - { - get { return _id; } - } - - // zb-00036 #29889 : removed unused field - // zb-00036 #29889 : removed PropertyTypes property (not making sense) - - public int ContentType - { - get { return _contenttype.Id; } - } - - private readonly string _caption; - - /// - /// The text on the tab - /// - /// - public string Caption - { - get - { - if (!_caption.StartsWith("#")) - return _caption; - - var lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); - if (lang != null) - { - if (Current.Services.LocalizationService.DictionaryItemExists(_caption.Substring(1, _caption.Length - 1))) - { - var di = Current.Services.LocalizationService.GetDictionaryItemByKey(_caption.Substring(1, _caption.Length - 1)); - return di.GetTranslatedValue(lang.id); - } - } - - return "[" + _caption + "]"; - } - } - } - #endregion - } -} diff --git a/src/umbraco.cms/businesslogic/LegacySqlHelper.cs b/src/umbraco.cms/businesslogic/LegacySqlHelper.cs deleted file mode 100644 index 1ff5518fcc..0000000000 --- a/src/umbraco.cms/businesslogic/LegacySqlHelper.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Configuration; -using umbraco.DataLayer; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; - -namespace umbraco.cms.businesslogic -{ - [Obsolete("Remove this! This is a temporary class whilst we refactor out old code")] - internal class LegacySqlHelper - { - private static ISqlHelper _sqlHelper; - - /// - /// Gets the SQL helper. - /// - /// The SQL helper. - [Obsolete("Do not use SqlHelper anymore, if database querying needs to be done use the DatabaseContext instead")] - public static ISqlHelper SqlHelper - { - get - { - if (_sqlHelper == null) - { - var connectionString = string.Empty; - - try - { - const string umbracoDsn = Constants.System.UmbracoConnectionName; - - var databaseSettings = ConfigurationManager.ConnectionStrings[umbracoDsn]; - if (databaseSettings != null) - connectionString = databaseSettings.ConnectionString; - - // During upgrades we might still have the old appSettings connectionstring, and not the new one, so get that one instead - if (string.IsNullOrWhiteSpace(connectionString) && - ConfigurationManager.AppSettings.ContainsKey(umbracoDsn)) - connectionString = ConfigurationManager.AppSettings[umbracoDsn]; - - _sqlHelper = DataLayerHelper.CreateSqlHelper(connectionString, false); - } - catch(Exception ex) - { - Current.Logger.Error(string.Format("Can't instantiate SQLHelper with connectionstring \"{0}\"", connectionString), ex); - } - } - - return _sqlHelper; - } - } - - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.Designer.cs b/src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.Designer.cs deleted file mode 100644 index 0d0b9c03e2..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.Designer.cs +++ /dev/null @@ -1,73 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace umbraco.cms.businesslogic.Packager.FileResources { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class PackageFiles { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal PackageFiles() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("umbraco.cms.businesslogic.Packager.FileResources.PackageFiles", typeof(PackageFiles).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8"?> - ///<packages></packages>. - /// - internal static string Packages { - get { - return ResourceManager.GetString("Packages", resourceCulture); - } - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.resx b/src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.resx deleted file mode 100644 index 264a983103..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/FileResources/PackageFiles.resx +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - packages.config;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/Packager/FileResources/Packages.config b/src/umbraco.cms/businesslogic/Packager/FileResources/Packages.config deleted file mode 100644 index 7be527318c..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/FileResources/Packages.config +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/Packager/Installer.cs b/src/umbraco.cms/businesslogic/Packager/Installer.cs deleted file mode 100644 index ddc63497c8..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/Installer.cs +++ /dev/null @@ -1,803 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Globalization; -using System.IO; -using System.Xml; -using System.Linq; -using ICSharpCode.SharpZipLib.Zip; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using umbraco.cms.businesslogic.web; -using System.Diagnostics; -using Umbraco.Core.Models; -using Umbraco.Core.Composing; -using Umbraco.Core.Events; -using Umbraco.Core.Models.Packaging; -using Umbraco.Core.Services; -using Umbraco.Core.Xml; -using File = System.IO.File; -using Macro = umbraco.cms.businesslogic.macro.Macro; -using Template = umbraco.cms.businesslogic.template.Template; - -namespace umbraco.cms.businesslogic.packager -{ - /// - /// The packager is a component which enables sharing of both data and functionality components between different umbraco installations. - /// - /// The output is a .umb (a zip compressed file) which contains the exported documents/medias/macroes/documenttypes (etc.) - /// in a Xml document, along with the physical files used (images/usercontrols/xsl documents etc.) - /// - /// Partly implemented, import of packages is done, the export is *under construction*. - /// - /// - /// Ruben Verborgh 31/12/2007: I had to change some code, I marked my changes with "DATALAYER". - /// Reason: @@IDENTITY can't be used with the new datalayer. - /// I wasn't able to test the code, since I'm not aware how the code functions. - /// - public class Installer - { - private const string PackageServer = "packages.umbraco.org"; - - private readonly List _unsecureFiles = new List(); - private readonly Dictionary _conflictingMacroAliases = new Dictionary(); - private readonly Dictionary _conflictingTemplateAliases = new Dictionary(); - private readonly Dictionary _conflictingStyleSheetNames = new Dictionary(); - - private readonly List _binaryFileErrors = new List(); - private int _currentUserId = -1; - - - public string Name { get; private set; } - public string Version { get; private set; } - public string Url { get; private set; } - public string License { get; private set; } - public string LicenseUrl { get; private set; } - public string Author { get; private set; } - public string AuthorUrl { get; private set; } - public string ReadMe { get; private set; } - public string Control { get; private set; } - - public bool ContainsMacroConflict { get; private set; } - public IDictionary ConflictingMacroAliases { get { return _conflictingMacroAliases; } } - - public bool ContainsUnsecureFiles { get; private set; } - public List UnsecureFiles { get { return _unsecureFiles; } } - - public bool ContainsTemplateConflicts { get; private set; } - public IDictionary ConflictingTemplateAliases { get { return _conflictingTemplateAliases; } } - - /// - /// Indicates that the package contains assembly reference errors - /// - public bool ContainsBinaryFileErrors { get; private set; } - - /// - /// List each assembly reference error - /// - public List BinaryFileErrors { get { return _binaryFileErrors; } } - - public bool ContainsStyleSheeConflicts { get; private set; } - public IDictionary ConflictingStyleSheetNames { get { return _conflictingStyleSheetNames; } } - - public int RequirementsMajor { get; private set; } - public int RequirementsMinor { get; private set; } - public int RequirementsPatch { get; private set; } - - public RequirementsType RequirementsType { get; private set; } - - public string IconUrl { get; private set; } - - /// - /// The xmldocument, describing the contents of a package. - /// - public XmlDocument Config { get; private set; } - - /// - /// Constructor - /// - public Installer() - { - Initialize(); - } - - public Installer(int currentUserId) - { - Initialize(); - _currentUserId = currentUserId; - } - - private void Initialize() - { - ContainsBinaryFileErrors = false; - ContainsTemplateConflicts = false; - ContainsUnsecureFiles = false; - ContainsMacroConflict = false; - ContainsStyleSheeConflicts = false; - } - - [Obsolete("Use the ctor with all parameters")] - [EditorBrowsable(EditorBrowsableState.Never)] - public Installer(string name, string version, string url, string license, string licenseUrl, string author, string authorUrl, int requirementsMajor, int requirementsMinor, int requirementsPatch, string readme, string control) - { - } - - /// - /// Constructor - /// - /// The name of the package - /// The version of the package - /// The url to a descriptionpage - /// The license under which the package is released (preferably GPL ;)) - /// The url to a licensedescription - /// The original author of the package - /// The url to the Authors website - /// Umbraco version major - /// Umbraco version minor - /// Umbraco version patch - /// The readme text - /// The name of the usercontrol used to configure the package after install - /// - /// - public Installer(string name, string version, string url, string license, string licenseUrl, string author, string authorUrl, int requirementsMajor, int requirementsMinor, int requirementsPatch, string readme, string control, RequirementsType requirementsType, string iconUrl) - { - ContainsBinaryFileErrors = false; - ContainsTemplateConflicts = false; - ContainsUnsecureFiles = false; - ContainsMacroConflict = false; - ContainsStyleSheeConflicts = false; - this.Name = name; - this.Version = version; - this.Url = url; - this.License = license; - this.LicenseUrl = licenseUrl; - this.RequirementsMajor = requirementsMajor; - this.RequirementsMinor = requirementsMinor; - this.RequirementsPatch = requirementsPatch; - this.RequirementsType = requirementsType; - this.Author = author; - this.AuthorUrl = authorUrl; - this.IconUrl = iconUrl; - ReadMe = readme; - this.Control = control; - } - - #region Public Methods - - /// - /// Imports the specified package - /// - /// Filename of the umbracopackage - /// true if the input file should be deleted after import - /// - public string Import(string inputFile, bool deleteFile) - { - using (Current.ProfilingLogger.DebugDuration( - $"Importing package file {inputFile}.", - $"Package file {inputFile} imported.")) - { - var tempDir = ""; - if (File.Exists(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile))) - { - var fi = new FileInfo(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile)); - // Check if the file is a valid package - if (fi.Extension.ToLower() == ".umb") - { - try - { - tempDir = UnPack(fi.FullName, deleteFile); - LoadConfig(tempDir); - } - catch (Exception exception) - { - Current.Logger.Error(string.Format("Error importing file {0}", fi.FullName), exception); - throw; - } - } - else - throw new Exception("Error - file isn't a package (doesn't have a .umb extension). Check if the file automatically got named '.zip' upon download."); - } - else - throw new Exception("Error - file not found. Could find file named '" + IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile) + "'"); - return tempDir; - } - - } - - /// - /// Imports the specified package - /// - /// Filename of the umbracopackage - /// - public string Import(string inputFile) - { - return Import(inputFile, true); - } - - public int CreateManifest(string tempDir, string guid, string repoGuid) - { - //This is the new improved install rutine, which chops up the process into 3 steps, creating the manifest, moving files, and finally handling umb objects - var packName = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name")); - var packAuthor = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name")); - var packAuthorUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website")); - var packVersion = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version")); - var packReadme = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme")); - var packLicense = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license ")); - var packUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url ")); - var iconUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/iconUrl")); - - var enableSkins = false; - var skinRepoGuid = ""; - - if (Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins") != null) - { - var skinNode = Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins"); - enableSkins = bool.Parse(XmlHelper.GetNodeValue(skinNode)); - if (skinNode.Attributes["repository"] != null && string.IsNullOrEmpty(skinNode.Attributes["repository"].Value) == false) - skinRepoGuid = skinNode.Attributes["repository"].Value; - } - - //Create a new package instance to record all the installed package adds - this is the same format as the created packages has. - //save the package meta data - var insPack = InstalledPackage.MakeNew(packName); - insPack.Data.Author = packAuthor; - insPack.Data.AuthorUrl = packAuthorUrl; - insPack.Data.Version = packVersion; - insPack.Data.Readme = packReadme; - insPack.Data.License = packLicense; - insPack.Data.Url = packUrl; - insPack.Data.IconUrl = iconUrl; - - //skinning - insPack.Data.EnableSkins = enableSkins; - insPack.Data.SkinRepoGuid = string.IsNullOrEmpty(skinRepoGuid) ? Guid.Empty : new Guid(skinRepoGuid); - - insPack.Data.PackageGuid = guid; //the package unique key. - insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged. - insPack.Save(); - - return insPack.Data.Id; - } - - public void InstallFiles(int packageId, string tempDir) - { - using (Current.ProfilingLogger.DebugDuration( - "Installing package files for package id " + packageId + " into temp folder " + tempDir, - "Package file installation complete for package id " + packageId)) - { - //retrieve the manifest to continue installation - var insPack = InstalledPackage.GetById(packageId); - - //TODO: Depending on some files, some files should be installed differently. - //i.e. if stylsheets should probably be installed via business logic, media items should probably use the media IFileSystem! - - // Move files - //string virtualBasePath = System.Web.HttpContext.Current.Request.ApplicationPath; - string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; - - try - { - foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file")) - { - var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath"))); - var sourceFile = GetFileName(tempDir, XmlHelper.GetNodeValue(n.SelectSingleNode("guid"))); - var destFile = GetFileName(destPath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"))); - - // Create the destination directory if it doesn't exist - if (Directory.Exists(destPath) == false) - Directory.CreateDirectory(destPath); - //If a file with this name exists, delete it - else if (File.Exists(destFile)) - File.Delete(destFile); - - // Copy the file - // SJ: Note - this used to do a move but some packages included the same file to be - // copied to multiple locations like so: - // - // - // my-icon.png - // /umbraco/Images/ - // my-icon.png - // - // - // my-icon.png - // /App_Plugins/MyPlugin/Images - // my-icon.png - // - // - // Since this file unzips as a flat list of files, moving the file the first time means - // that when you try to do that a second time, it would result in a FileNotFoundException - File.Copy(sourceFile, destFile); - - //PPH log file install - insPack.Data.Files.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"))); - - } - - // Once we're done copying, remove all the files - foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file")) - { - var sourceFile = GetFileName(tempDir, XmlHelper.GetNodeValue(n.SelectSingleNode("guid"))); - if (File.Exists(sourceFile)) - File.Delete(sourceFile); - } - } - catch (Exception exception) - { - Current.Logger.Error("Package install error", exception); - throw; - } - - // log that a user has install files - if (_currentUserId > -1) - { - Current.Services.AuditService.Add(AuditType.PackagerInstall, - string.Format("Package '{0}' installed. Package guid: {1}", insPack.Data.Name, insPack.Data.PackageGuid), - _currentUserId, -1); - } - - insPack.Save(); - } - } - - public void InstallBusinessLogic(int packageId, string tempDir) - { - using (Current.ProfilingLogger.DebugDuration( - "Installing business logic for package id " + packageId + " into temp folder " + tempDir, - "Package business logic installation complete for package id " + packageId)) - { - InstalledPackage insPack; - try - { - //retrieve the manifest to continue installation - insPack = InstalledPackage.GetById(packageId); - //bool saveNeeded = false; - - // Get current user, with a fallback - var currentUser = Current.Services.UserService.GetUserById(0); - - //TODO: Get rid of this entire class! Until then all packages will be installed by the admin user - - - //Xml as XElement which is used with the new PackagingService - var rootElement = Config.DocumentElement.GetXElement(); - var packagingService = Current.Services.PackagingService; - - //Perhaps it would have been a good idea to put the following into methods eh?!? - - #region DataTypes - var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault(); - if (dataTypeElement != null) - { - var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id); - foreach (var dataTypeDefinition in dataTypeDefinitions) - { - insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture)); - } - } - #endregion - - #region Languages - var languageItemsElement = rootElement.Descendants("Languages").FirstOrDefault(); - if (languageItemsElement != null) - { - var insertedLanguages = packagingService.ImportLanguages(languageItemsElement); - insPack.Data.Languages.AddRange(insertedLanguages.Select(l => l.Id.ToString(CultureInfo.InvariantCulture))); - } - - #endregion - - #region Dictionary items - var dictionaryItemsElement = rootElement.Descendants("DictionaryItems").FirstOrDefault(); - if (dictionaryItemsElement != null) - { - var insertedDictionaryItems = packagingService.ImportDictionaryItems(dictionaryItemsElement); - insPack.Data.DictionaryItems.AddRange(insertedDictionaryItems.Select(d => d.Id.ToString(CultureInfo.InvariantCulture))); - } - #endregion - - #region Macros - var macroItemsElement = rootElement.Descendants("Macros").FirstOrDefault(); - if (macroItemsElement != null) - { - var insertedMacros = packagingService.ImportMacros(macroItemsElement); - insPack.Data.Macros.AddRange(insertedMacros.Select(m => m.Id.ToString(CultureInfo.InvariantCulture))); - } - #endregion - - #region Templates - var templateElement = rootElement.Descendants("Templates").FirstOrDefault(); - if (templateElement != null) - { - var templates = packagingService.ImportTemplates(templateElement, currentUser.Id); - foreach (var template in templates) - { - insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture)); - } - } - #endregion - - #region DocumentTypes - //Check whether the root element is a doc type rather then a complete package - var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") || - rootElement.Name.LocalName.Equals("DocumentTypes") - ? rootElement - : rootElement.Descendants("DocumentTypes").FirstOrDefault(); - - if (docTypeElement != null) - { - var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id); - foreach (var contentType in contentTypes) - { - insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture)); - //saveNeeded = true; - } - } - #endregion - - #region Stylesheets - foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet")) - { - StyleSheet s = StyleSheet.Import(n, currentUser); - - insPack.Data.Stylesheets.Add(s.Id.ToString(CultureInfo.InvariantCulture)); - //saveNeeded = true; - } - - //if (saveNeeded) { insPack.Save(); saveNeeded = false; } - #endregion - - #region Documents - var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault(); - if (documentElement != null) - { - var content = packagingService.ImportContent(documentElement, -1, currentUser.Id); - var firstContentItem = content.First(); - insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture); - } - #endregion - - #region Package Actions - foreach (XmlNode n in Config.DocumentElement.SelectNodes("Actions/Action")) - { - if (n.Attributes["undo"] == null || n.Attributes["undo"].Value == "true") - { - insPack.Data.Actions += n.OuterXml; - } - - //Run the actions tagged only for 'install' - - if (n.Attributes["runat"] != null && n.Attributes["runat"].Value == "install") - { - var alias = n.Attributes["alias"] != null ? n.Attributes["alias"].Value : ""; - - if (alias.IsNullOrWhiteSpace() == false) - { - PackageAction.RunPackageAction(insPack.Data.Name, alias, n); - } - } - } - #endregion - - insPack.Save(); - } - catch (Exception exception) - { - Current.Logger.Error("Error installing businesslogic", exception); - throw; - } - - OnPackageBusinessLogicInstalled(insPack); - OnPackageInstalled(insPack); - } - } - - /// - /// Remove the temp installation folder - /// - /// - /// - public void InstallCleanUp(int packageId, string tempDir) - { - if (Directory.Exists(tempDir)) - { - Directory.Delete(tempDir, true); - } - } - - /// - /// Reads the configuration of the package from the configuration xmldocument - /// - /// The folder to which the contents of the package is extracted - public void LoadConfig(string tempDir) - { - Config = new XmlDocument(); - Config.Load(tempDir + Path.DirectorySeparatorChar + "package.xml"); - - Name = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name").FirstChild.Value; - Version = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version").FirstChild.Value; - Url = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url").FirstChild.Value; - License = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").FirstChild.Value; - LicenseUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").Attributes.GetNamedItem("url").Value; - - RequirementsMajor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/major").FirstChild.Value); - RequirementsMinor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/minor").FirstChild.Value); - RequirementsPatch = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/patch").FirstChild.Value); - - var reqNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements"); - RequirementsType = reqNode != null && reqNode.Attributes != null && reqNode.Attributes["type"] != null - ? Enum.Parse(reqNode.Attributes["type"].Value, true) - : RequirementsType.Legacy; - var iconNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/iconUrl"); - if (iconNode != null && iconNode.FirstChild != null) - { - IconUrl = iconNode.FirstChild.Value; - } - - Author = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name").FirstChild.Value; - AuthorUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website").FirstChild.Value; - - var basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; - var dllBinFiles = new List(); - - foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file")) - { - var badFile = false; - var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath"))); - var orgName = XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")); - var destFile = GetFileName(destPath, orgName); - - if (destPath.ToLower().Contains(IOHelper.DirSepChar + "app_code")) - { - badFile = true; - } - - if (destPath.ToLower().Contains(IOHelper.DirSepChar + "bin")) - { - badFile = true; - } - - if (destFile.ToLower().EndsWith(".dll")) - { - badFile = true; - dllBinFiles.Add(Path.Combine(tempDir, orgName)); - } - - if (badFile) - { - ContainsUnsecureFiles = true; - _unsecureFiles.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"))); - } - } - - - - //this will check for existing macros with the same alias - //since we will not overwrite on import it's a good idea to inform the user what will be overwritten - foreach (XmlNode n in Config.DocumentElement.SelectNodes("//macro")) - { - var alias = n.SelectSingleNode("alias").InnerText; - if (!string.IsNullOrEmpty(alias)) - { - var m = Current.Services.MacroService.GetByAlias(alias); - if (m != null) - { - ContainsMacroConflict = true; - if (_conflictingMacroAliases.ContainsKey(m.Name) == false) - { - _conflictingMacroAliases.Add(m.Name, alias); - } - } - } - } - - foreach (XmlNode n in Config.DocumentElement.SelectNodes("Templates/Template")) - { - var alias = n.SelectSingleNode("Alias").InnerText; - if (!string.IsNullOrEmpty(alias)) - { - var t = Template.GetByAlias(alias); - if (t != null) - { - ContainsTemplateConflicts = true; - if (_conflictingTemplateAliases.ContainsKey(t.Text) == false) - { - _conflictingTemplateAliases.Add(t.Text, alias); - } - } - } - } - - foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet")) - { - var alias = n.SelectSingleNode("Name").InnerText; - if (!string.IsNullOrEmpty(alias)) - { - var s = StyleSheet.GetByName(alias); - if (s != null) - { - ContainsStyleSheeConflicts = true; - if (_conflictingStyleSheetNames.ContainsKey(s.Text) == false) - { - _conflictingStyleSheetNames.Add(s.Text, alias); - } - } - } - } - - var readmeNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme"); - if (readmeNode != null) - { - ReadMe = XmlHelper.GetNodeValue(readmeNode); - } - - var controlNode = Config.DocumentElement.SelectSingleNode("/umbPackage/control"); - if (controlNode != null) - { - Control = XmlHelper.GetNodeValue(controlNode); - } - } - - /// - /// This uses the old method of fetching and only supports the packages.umbraco.org repository. - /// - /// - /// - public string Fetch(Guid Package) - { - // Check for package directory - if (Directory.Exists(IOHelper.MapPath(SystemDirectories.Packages)) == false) - Directory.CreateDirectory(IOHelper.MapPath(SystemDirectories.Packages)); - - var wc = new System.Net.WebClient(); - - wc.DownloadFile( - "http://" + PackageServer + "/fetch?package=" + Package.ToString(), - IOHelper.MapPath(SystemDirectories.Packages + "/" + Package + ".umb")); - - return "packages\\" + Package + ".umb"; - } - - #endregion - - #region Private Methods - - /// - /// Gets the name of the file in the specified path. - /// Corrects possible problems with slashes that would result from a simple concatenation. - /// Can also be used to concatenate paths. - /// - /// The path. - /// Name of the file. - /// The name of the file in the specified path. - private static string GetFileName(string path, string fileName) - { - // virtual dir support - fileName = IOHelper.FindFile(fileName); - - if (path.Contains("[$")) - { - //this is experimental and undocumented... - path = path.Replace("[$UMBRACO]", SystemDirectories.Umbraco); - path = path.Replace("[$UMBRACOCLIENT]", SystemDirectories.UmbracoClient); - path = path.Replace("[$CONFIG]", SystemDirectories.Config); - path = path.Replace("[$DATA]", SystemDirectories.Data); - } - - //to support virtual dirs we try to lookup the file... - path = IOHelper.FindFile(path); - - - - Debug.Assert(path != null && path.Length >= 1); - Debug.Assert(fileName != null && fileName.Length >= 1); - - path = path.Replace('/', '\\'); - fileName = fileName.Replace('/', '\\'); - - // Does filename start with a slash? Does path end with one? - bool fileNameStartsWithSlash = (fileName[0] == Path.DirectorySeparatorChar); - bool pathEndsWithSlash = (path[path.Length - 1] == Path.DirectorySeparatorChar); - - // Path ends with a slash - if (pathEndsWithSlash) - { - if (!fileNameStartsWithSlash) - // No double slash, just concatenate - return path + fileName; - return path + fileName.Substring(1); - } - if (fileNameStartsWithSlash) - // Required slash specified, just concatenate - return path + fileName; - return path + Path.DirectorySeparatorChar + fileName; - } - - private static string UnPack(string zipName, bool deleteFile) - { - // Unzip - - //the temp directory will be the package GUID - this keeps it consistent! - //the zipName is always the package Guid.umb - - var packageFileName = Path.GetFileNameWithoutExtension(zipName); - var packageId = Guid.NewGuid(); - Guid.TryParse(packageFileName, out packageId); - - string tempDir = IOHelper.MapPath(SystemDirectories.Data) + Path.DirectorySeparatorChar + packageId.ToString(); - //clear the directory if it exists - if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); - Directory.CreateDirectory(tempDir); - - var s = new ZipInputStream(File.OpenRead(zipName)); - - ZipEntry theEntry; - while ((theEntry = s.GetNextEntry()) != null) - { - string fileName = Path.GetFileName(theEntry.Name); - - if (fileName != String.Empty) - { - FileStream streamWriter = File.Create(tempDir + Path.DirectorySeparatorChar + fileName); - - int size = 2048; - byte[] data = new byte[2048]; - while (true) - { - size = s.Read(data, 0, data.Length); - if (size > 0) - { - streamWriter.Write(data, 0, size); - } - else - { - break; - } - } - - streamWriter.Close(); - - } - } - - // Clean up - s.Close(); - - if (deleteFile) - { - File.Delete(zipName); - } - - - return tempDir; - - } - - #endregion - - internal static event EventHandler PackageBusinessLogicInstalled; - - private static void OnPackageBusinessLogicInstalled(InstalledPackage e) - { - EventHandler handler = PackageBusinessLogicInstalled; - if (handler != null) handler(null, e); - } - - private void OnPackageInstalled(InstalledPackage insPack) - { - // getting an InstallationSummary for sending to the PackagingService.ImportedPackage event - var fileService = Current.Services.FileService; - var macroService = Current.Services.MacroService; - var contentTypeService = Current.Services.ContentTypeService; - var dataTypeService = Current.Services.DataTypeService; - var localizationService = Current.Services.LocalizationService; - - var installationSummary = insPack.GetInstallationSummary(contentTypeService, dataTypeService, fileService, localizationService, macroService); - installationSummary.PackageInstalled = true; - - var args = new ImportPackageEventArgs(installationSummary, false); - PackagingService.OnImportedPackage(args); - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/Package.cs b/src/umbraco.cms/businesslogic/Packager/Package.cs deleted file mode 100644 index 77fa831621..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/Package.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using umbraco.BusinessLogic; -using umbraco.DataLayer; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; - -namespace umbraco.cms.businesslogic.packager -{ - [Obsolete("This class is not used and will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - public class Package - { - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - - public Package() - { - } - - /// - /// Initialize package install status object by specifying the internal id of the installation. - /// The id is specific to the local umbraco installation and cannot be used to identify the package in general. - /// Use the Package(Guid) constructor to check whether a package has been installed - /// - /// The internal id. - public Package(int Id) - { - Initialize(Id); - } - - public Package(Guid Id) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - int installStatusId = sqlHelper.ExecuteScalar( - "select id from umbracoInstalledPackages where package = @package and upgradeId = 0", - sqlHelper.CreateParameter("@package", Id)); - - if (installStatusId > 0) - Initialize(installStatusId); - else - throw new ArgumentException("Package with id '" + Id.ToString() + "' is not installed"); - } - } - - private void Initialize(int id) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) { - using (IRecordsReader dr = - sqlHelper.ExecuteReader( - "select id, uninstalled, upgradeId, installDate, userId, package, versionMajor, versionMinor, versionPatch from umbracoInstalledPackages where id = @id", - sqlHelper.CreateParameter("@id", id))) - { - if (dr.Read()) - { - Id = id; - Uninstalled = dr.GetBoolean("uninstalled"); - UpgradeId = dr.GetInt("upgradeId"); - InstallDate = dr.GetDateTime("installDate"); - User = Current.Services.UserService.GetUserById(dr.GetInt("userId")); - PackageId = dr.GetGuid("package"); - VersionMajor = dr.GetInt("versionMajor"); - VersionMinor = dr.GetInt("versionMinor"); - VersionPatch = dr.GetInt("versionPatch"); - } - } - } - } - - [MethodImpl(MethodImplOptions.Synchronized)] - public void Save() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - IParameter[] values = { - sqlHelper.CreateParameter("@uninstalled", Uninstalled), - sqlHelper.CreateParameter("@upgradeId", UpgradeId), - sqlHelper.CreateParameter("@installDate", InstallDate), - sqlHelper.CreateParameter("@userId", User.Id), - sqlHelper.CreateParameter("@versionMajor", VersionMajor), - sqlHelper.CreateParameter("@versionMinor", VersionMinor), - sqlHelper.CreateParameter("@versionPatch", VersionPatch), - sqlHelper.CreateParameter("@id", Id) - }; - - // check if package status exists - if (Id == 0) - { - // The method is synchronized - sqlHelper.ExecuteNonQuery("INSERT INTO umbracoInstalledPackages (uninstalled, upgradeId, installDate, userId, versionMajor, versionMinor, versionPatch) VALUES (@uninstalled, @upgradeId, @installDate, @userId, @versionMajor, @versionMinor, @versionPatch)", values); - Id = sqlHelper.ExecuteScalar("SELECT MAX(id) FROM umbracoInstalledPackages"); - } - - sqlHelper.ExecuteNonQuery( - "update umbracoInstalledPackages set " + - "uninstalled = @uninstalled, " + - "upgradeId = @upgradeId, " + - "installDate = @installDate, " + - "userId = @userId, " + - "versionMajor = @versionMajor, " + - "versionMinor = @versionMinor, " + - "versionPatch = @versionPatch " + - "where id = @id", - values); - } - } - - public bool Uninstalled { get; set; } - - - public IUser User { get; set; } - - - public DateTime InstallDate { get; set; } - - - public int Id { get; set; } - - - public int UpgradeId { get; set; } - - - public Guid PackageId { get; set; } - - - public int VersionPatch { get; set; } - - - public int VersionMinor { get; set; } - - - public int VersionMajor { get; set; } - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/CreatedPackage.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/CreatedPackage.cs deleted file mode 100644 index 207b40c6e7..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/CreatedPackage.cs +++ /dev/null @@ -1,376 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml; -using System.Web; -using Newtonsoft.Json; -using Umbraco.Core; -using Umbraco.Core.Logging; -using umbraco.cms.businesslogic.web; -using umbraco.cms.businesslogic.macro; -using Umbraco.Core.Composing; -using Umbraco.Core.IO; -using Umbraco.Core.Models; -using Umbraco.Core.Services; -using File = System.IO.File; -using Template = umbraco.cms.businesslogic.template.Template; - - -namespace umbraco.cms.businesslogic.packager -{ - public class CreatedPackage - { - - public static CreatedPackage GetById(int id) - { - var pack = new CreatedPackage(); - pack.Data = data.Package(id, IOHelper.MapPath(Settings.CreatedPackagesSettings)); - return pack; - } - - public static CreatedPackage MakeNew(string name) - { - var pack = new CreatedPackage - { - Data = data.MakeNew(name, IOHelper.MapPath(Settings.CreatedPackagesSettings)) - }; - - - return pack; - } - - public void Save() - { - data.Save(this.Data, IOHelper.MapPath(Settings.CreatedPackagesSettings)); - } - - public void Delete() - { - data.Delete(this.Data.Id, IOHelper.MapPath(Settings.CreatedPackagesSettings)); - } - - public PackageInstance Data { get; set; } - - public static List GetAllCreatedPackages() - { - var val = new List(); - - foreach (var pack in data.GetAllPackages(IOHelper.MapPath(Settings.CreatedPackagesSettings))) - { - var crPack = new CreatedPackage(); - crPack.Data = pack; - val.Add(crPack); - } - - return val; - } - - private static XmlDocument _packageManifest; - private static void CreatePackageManifest() - { - _packageManifest = new XmlDocument(); - var xmldecl = _packageManifest.CreateXmlDeclaration("1.0", "UTF-8", "no"); - - _packageManifest.AppendChild(xmldecl); - - //root node - XmlNode umbPackage = _packageManifest.CreateElement("umbPackage"); - _packageManifest.AppendChild(umbPackage); - //Files node - umbPackage.AppendChild(_packageManifest.CreateElement("files")); - } - - private static void AppendElement(XmlNode node) - { - var root = _packageManifest.SelectSingleNode("/umbPackage"); - root.AppendChild(node); - } - - - public void Publish() - { - - var package = this; - var pack = package.Data; - - var outInt = 0; - - //Path checking... - var localPath = IOHelper.MapPath(SystemDirectories.Media + "/" + pack.Folder); - - if (Directory.Exists(localPath) == false) - Directory.CreateDirectory(localPath); - - //Init package file... - CreatePackageManifest(); - //Info section.. - AppendElement(PackagerUtility.PackageInfo(pack, _packageManifest)); - - //Documents and tags... - var contentNodeId = 0; - if (string.IsNullOrEmpty(pack.ContentNodeId) == false && int.TryParse(pack.ContentNodeId, out contentNodeId)) - { - if (contentNodeId > 0) - { - //Create the Documents/DocumentSet node - XmlNode documents = _packageManifest.CreateElement("Documents"); - XmlNode documentSet = _packageManifest.CreateElement("DocumentSet"); - XmlAttribute importMode = _packageManifest.CreateAttribute("importMode", ""); - importMode.Value = "root"; - documentSet.Attributes.Append(importMode); - documents.AppendChild(documentSet); - - //load content from umbraco. - var umbDocument = new Document(contentNodeId); - - documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes)); - - AppendElement(documents); - - ////Create the TagProperties node - this is used to store a definition for all - //// document properties that are tags, this ensures that we can re-import tags properly - //XmlNode tagProps = _packageManifest.CreateElement("TagProperties"); - - ////before we try to populate this, we'll do a quick lookup to see if any of the documents - //// being exported contain published tags. - //var allExportedIds = documents.SelectNodes("//@id").Cast() - // .Select(x => x.Value.TryConvertTo()) - // .Where(x => x.Success) - // .Select(x => x.Result) - // .ToArray(); - //var allContentTags = new List(); - //foreach (var exportedId in allExportedIds) - //{ - // allContentTags.AddRange( - // Current.Services.TagService.GetTagsForEntity(exportedId)); - //} - - ////This is pretty round-about but it works. Essentially we need to get the properties that are tagged - //// but to do that we need to lookup by a tag (string) - //var allTaggedEntities = new List(); - //foreach (var group in allContentTags.Select(x => x.Group).Distinct()) - //{ - // allTaggedEntities.AddRange( - // Current.Services.TagService.GetTaggedContentByTagGroup(group)); - //} - - ////Now, we have all property Ids/Aliases and their referenced document Ids and tags - //var allExportedTaggedEntities = allTaggedEntities.Where(x => allExportedIds.Contains(x.EntityId)) - // .DistinctBy(x => x.EntityId) - // .OrderBy(x => x.EntityId); - - //foreach (var taggedEntity in allExportedTaggedEntities) - //{ - // foreach (var taggedProperty in taggedEntity.TaggedProperties.Where(x => x.Tags.Any())) - // { - // XmlNode tagProp = _packageManifest.CreateElement("TagProperty"); - // var docId = _packageManifest.CreateAttribute("docId", ""); - // docId.Value = taggedEntity.EntityId.ToString(CultureInfo.InvariantCulture); - // tagProp.Attributes.Append(docId); - - // var propertyAlias = _packageManifest.CreateAttribute("propertyAlias", ""); - // propertyAlias.Value = taggedProperty.PropertyTypeAlias; - // tagProp.Attributes.Append(propertyAlias); - - // var group = _packageManifest.CreateAttribute("group", ""); - // group.Value = taggedProperty.Tags.First().Group; - // tagProp.Attributes.Append(group); - - // tagProp.AppendChild(_packageManifest.CreateCDataSection( - // JsonConvert.SerializeObject(taggedProperty.Tags.Select(x => x.Text).ToArray()))); - - // tagProps.AppendChild(tagProp); - // } - //} - - //AppendElement(tagProps); - - } - } - - //Document types.. - var dtl = new List(); - var docTypes = _packageManifest.CreateElement("DocumentTypes"); - foreach (var dtId in pack.Documenttypes) - { - if (int.TryParse(dtId, out outInt)) - { - DocumentType docT = new DocumentType(outInt); - - AddDocumentType(docT, ref dtl); - - } - } - - foreach (DocumentType d in dtl) - { - docTypes.AppendChild(d.ToXml(_packageManifest)); - } - - AppendElement(docTypes); - - //Templates - var templates = _packageManifest.CreateElement("Templates"); - foreach (var templateId in pack.Templates) - { - if (int.TryParse(templateId, out outInt)) - { - var t = new Template(outInt); - templates.AppendChild(t.ToXml(_packageManifest)); - } - } - AppendElement(templates); - - //Stylesheets - var stylesheets = _packageManifest.CreateElement("Stylesheets"); - foreach (var stylesheetName in pack.Stylesheets) - { - if (stylesheetName.IsNullOrWhiteSpace()) continue; - var stylesheetXmlNode = PackagerUtility.Stylesheet(stylesheetName, true, _packageManifest); - if (stylesheetXmlNode != null) - stylesheets.AppendChild(stylesheetXmlNode); - } - AppendElement(stylesheets); - - //Macros - var macros = _packageManifest.CreateElement("Macros"); - foreach (var macroId in pack.Macros) - { - if (int.TryParse(macroId, out outInt)) - { - macros.AppendChild(PackagerUtility.Macro(int.Parse(macroId), true, localPath, _packageManifest)); - } - } - AppendElement(macros); - - //Dictionary Items - var dictionaryItems = _packageManifest.CreateElement("DictionaryItems"); - foreach (var dictionaryId in pack.DictionaryItems) - { - if (int.TryParse(dictionaryId, out outInt)) - { - var di = Current.Services.LocalizationService.GetDictionaryItemById(outInt); - var entitySerializer = new EntityXmlSerializer(); - var xmlNode = entitySerializer.Serialize(di).GetXmlNode(_packageManifest); - dictionaryItems.AppendChild(xmlNode); - } - } - AppendElement(dictionaryItems); - - //Languages - var languages = _packageManifest.CreateElement("Languages"); - foreach (var langId in pack.Languages) - { - if (int.TryParse(langId, out outInt)) - { - var lang = new language.Language(outInt); - - languages.AppendChild(lang.ToXml(_packageManifest)); - } - } - AppendElement(languages); - - //TODO: Fix this! ... actually once we use the new packager we don't need to - - ////Datatypes - //var dataTypes = _packageManifest.CreateElement("DataTypes"); - //foreach (var dtId in pack.DataTypes) - //{ - // if (int.TryParse(dtId, out outInt)) - // { - // datatype.DataTypeDefinition dtd = new datatype.DataTypeDefinition(outInt); - // dataTypes.AppendChild(dtd.ToXml(_packageManifest)); - // } - //} - //AppendElement(dataTypes); - - //Files - foreach (var fileName in pack.Files) - { - PackagerUtility.AppendFileToManifest(fileName, localPath, _packageManifest); - } - - //Load control on install... - if (string.IsNullOrEmpty(pack.LoadControl) == false) - { - XmlNode control = _packageManifest.CreateElement("control"); - control.InnerText = pack.LoadControl; - PackagerUtility.AppendFileToManifest(pack.LoadControl, localPath, _packageManifest); - AppendElement(control); - } - - //Actions - if (string.IsNullOrEmpty(pack.Actions) == false) - { - try - { - var xdActions = new XmlDocument(); - xdActions.LoadXml("" + pack.Actions + ""); - var actions = xdActions.DocumentElement.SelectSingleNode("."); - - - if (actions != null) - { - actions = _packageManifest.ImportNode(actions, true).Clone(); - AppendElement(actions); - } - } - catch { } - } - - var manifestFileName = localPath + "/package.xml"; - - if (File.Exists(manifestFileName)) - File.Delete(manifestFileName); - - _packageManifest.Save(manifestFileName); - _packageManifest = null; - - - //string packPath = Settings.PackagerRoot.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), "/") + "/" + pack.Name.Replace(' ', '_') + "_" + pack.Version.Replace(' ', '_') + "." + Settings.PackageFileExtension; - - // check if there's a packages directory below media - var packagesDirectory = SystemDirectories.Media + "/created-packages"; - if (Directory.Exists(IOHelper.MapPath(packagesDirectory)) == false) - { - Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory)); - } - - - var packPath = packagesDirectory + "/" + (pack.Name + "_" + pack.Version).Replace(' ', '_') + "." + Settings.PackageFileExtension; - PackagerUtility.ZipPackage(localPath, IOHelper.MapPath(packPath)); - - pack.PackagePath = packPath; - - if (pack.PackageGuid.Trim() == "") - pack.PackageGuid = Guid.NewGuid().ToString(); - - package.Save(); - - //Clean up.. - File.Delete(localPath + "/package.xml"); - Directory.Delete(localPath, true); - } - - private void AddDocumentType(DocumentType dt, ref List dtl) - { - if (dt.MasterContentType != 0 && dt.Parent.nodeObjectType == Constants.ObjectTypes.DocumentTypeGuid) - { - //first add masters - var mDocT = new DocumentType(dt.MasterContentType); - AddDocumentType(mDocT, ref dtl); - } - - if (dtl.Contains(dt) == false) - { - dtl.Add(dt); - } - } - - - - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/IPackageInstance.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/IPackageInstance.cs deleted file mode 100644 index 29e53339d6..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/IPackageInstance.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -namespace umbraco.cms.businesslogic.packager{ - public interface IPackageInstance { - string Actions { get; set; } - string Author { get; set; } - string AuthorUrl { get; set; } - bool ContentLoadChildNodes { get; set; } - string ContentNodeId { get; set; } - System.Collections.Generic.List Documenttypes { get; set; } - System.Collections.Generic.List Files { get; set; } - string Folder { get; set; } - bool HasUpdate { get; set; } - int Id { get; set; } - string License { get; set; } - string LicenseUrl { get; set; } - string LoadControl { get; set; } - System.Collections.Generic.List Macros { get; set; } - string Name { get; set; } - string PackageGuid { get; set; } - string PackagePath { get; set; } - string Readme { get; set; } - string RepositoryGuid { get; set; } - System.Collections.Generic.List Stylesheets { get; set; } - System.Collections.Generic.List Templates { get; set; } - string Url { get; set; } - string Version { get; set; } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs deleted file mode 100644 index 13388b1b0a..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs +++ /dev/null @@ -1,199 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; -using Umbraco.Core.IO; -using Umbraco.Core.Models; -using Umbraco.Core.Models.Packaging; -using Umbraco.Core.Services; - -namespace umbraco.cms.businesslogic.packager { - public class InstalledPackage - { - - private int _saveHitCount = 0; - - public static InstalledPackage GetById(int id) { - InstalledPackage pack = new InstalledPackage(); - pack.Data = data.Package(id, IOHelper.MapPath(Settings.InstalledPackagesSettings)); - return pack; - } - - public static InstalledPackage GetByGuid(string packageGuid) { - InstalledPackage pack = new InstalledPackage(); - pack.Data = data.Package(packageGuid, IOHelper.MapPath(Settings.InstalledPackagesSettings)); - return pack; - } - - public static InstalledPackage MakeNew(string name) { - InstalledPackage pack = new InstalledPackage(); - pack.Data = data.MakeNew(name, IOHelper.MapPath(Settings.InstalledPackagesSettings)); - pack.OnNew(EventArgs.Empty); - return pack; - } - - public void Save() - { -#if DEBUG - _saveHitCount++; - Current.Logger.Info("The InstalledPackage class save method has been hit " + _saveHitCount + " times."); -#endif - this.FireBeforeSave(EventArgs.Empty); - data.Save(this.Data, IOHelper.MapPath(Settings.InstalledPackagesSettings)); - this.FireAfterSave(EventArgs.Empty); - } - - public static List GetAllInstalledPackages() { - - List val = new List(); - - foreach (PackageInstance pack in data.GetAllPackages(IOHelper.MapPath(Settings.InstalledPackagesSettings))) - { - InstalledPackage insPackage = new InstalledPackage(); - insPackage.Data = pack; - val.Add(insPackage); - } - - return val; - } - - private PackageInstance m_data; - public PackageInstance Data { - get { return m_data; } - set { m_data = value; } - } - - public void Delete(int userId) - { - Current.Services.AuditService.Add(AuditType.PackagerUninstall, string.Format("Package '{0}' uninstalled. Package guid: {1}", Data.Name, Data.PackageGuid), userId, -1); - Delete(); - } - - public void Delete() { - this.FireBeforeDelete(EventArgs.Empty); - data.Delete(this.Data.Id, IOHelper.MapPath(Settings.InstalledPackagesSettings)); - this.FireAfterDelete(EventArgs.Empty); - } - - public static bool isPackageInstalled(string packageGuid) { - try - { - if (data.GetFromGuid(packageGuid, IOHelper.MapPath(Settings.InstalledPackagesSettings), true) == null) - return false; - else - return true; - } - catch (Exception ex) - { - Current.Logger.Error("An error occured in isPackagedInstalled", ex); - return false; - } - } - - //EVENTS - public delegate void SaveEventHandler(InstalledPackage sender, EventArgs e); - public delegate void NewEventHandler(InstalledPackage sender, EventArgs e); - public delegate void DeleteEventHandler(InstalledPackage sender, EventArgs e); - - /// - /// Occurs when a macro is saved. - /// - public static event SaveEventHandler BeforeSave; - protected virtual void FireBeforeSave(EventArgs e) { - if (BeforeSave != null) - BeforeSave(this, e); - } - - public static event SaveEventHandler AfterSave; - protected virtual void FireAfterSave(EventArgs e) { - if (AfterSave != null) - AfterSave(this, e); - } - - public static event NewEventHandler New; - protected virtual void OnNew(EventArgs e) { - if (New != null) - New(this, e); - } - - public static event DeleteEventHandler BeforeDelete; - protected virtual void FireBeforeDelete(EventArgs e) { - if (BeforeDelete != null) - BeforeDelete(this, e); - } - - public static event DeleteEventHandler AfterDelete; - protected virtual void FireAfterDelete(EventArgs e) { - if (AfterDelete != null) - AfterDelete(this, e); - } - - - /// - /// Used internally for creating an InstallationSummary (used in new PackagingService) representation of this InstalledPackage object. - /// - /// - /// - /// - /// - /// - /// - internal InstallationSummary GetInstallationSummary(IContentTypeService contentTypeService, IDataTypeService dataTypeService, IFileService fileService, ILocalizationService localizationService, IMacroService macroService) - { - var macros = TryGetIntegerIds(Data.Macros).Select(macroService.GetById).ToList(); - var templates = TryGetIntegerIds(Data.Templates).Select(fileService.GetTemplate).ToList(); - var contentTypes = TryGetIntegerIds(Data.Documenttypes).Select(contentTypeService.Get).ToList(); // fixme - media types? - var dataTypes = TryGetIntegerIds(Data.DataTypes).Select(dataTypeService.GetDataTypeDefinitionById).ToList(); - var dictionaryItems = TryGetIntegerIds(Data.DictionaryItems).Select(localizationService.GetDictionaryItemById).ToList(); - var languages = TryGetIntegerIds(Data.Languages).Select(localizationService.GetLanguageById).ToList(); - - for (var i = 0; i < Data.Files.Count; i++) - { - var filePath = Data.Files[i]; - Data.Files[i] = filePath.GetRelativePath(); - } - - return new InstallationSummary - { - ContentTypesInstalled = contentTypes, - DataTypesInstalled = dataTypes, - DictionaryItemsInstalled = dictionaryItems, - FilesInstalled = Data.Files, - LanguagesInstalled = languages, - MacrosInstalled = macros, - MetaData = GetMetaData(), - TemplatesInstalled = templates, - }; - } - - internal MetaData GetMetaData() - { - return new MetaData() - { - AuthorName = Data.Author, - AuthorUrl = Data.AuthorUrl, - Control = Data.LoadControl, - License = Data.License, - LicenseUrl = Data.LicenseUrl, - Name = Data.Name, - Readme = Data.Readme, - Url = Data.Url, - Version = Data.Version - }; - } - - private static IEnumerable TryGetIntegerIds(IEnumerable ids) - { - var intIds = new List(); - foreach (var id in ids) - { - int parsed; - if (int.TryParse(id, out parsed)) - intIds.Add(parsed); - } - return intIds; - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs deleted file mode 100644 index e9d75d230b..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Xml; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; -using Umbraco.Core._Legacy.PackageActions; - - -namespace umbraco.cms.businesslogic.packager -{ - - /// - /// Package actions are executed on packge install / uninstall. - /// - public class PackageAction - { - - /// - /// Runs the package action with the specified action alias. - /// - /// Name of the package. - /// The action alias. - /// The action XML. - public static void RunPackageAction(string packageName, string actionAlias, XmlNode actionXml) - { - - foreach (var ipa in Current.PackageActions) - { - try - { - if (ipa.Alias() == actionAlias) - { - - ipa.Execute(packageName, actionXml); - } - } - catch (Exception ipaExp) - { - Current.Logger.Error(string.Format("Error loading package action '{0}' for package {1}", ipa.Alias(), packageName), ipaExp); - } - } - } - - /// - /// Undos the package action with the specified action alias. - /// - /// Name of the package. - /// The action alias. - /// The action XML. - public static void UndoPackageAction(string packageName, string actionAlias, System.Xml.XmlNode actionXml) - { - - foreach (IPackageAction ipa in Current.PackageActions) - { - try - { - if (ipa.Alias() == actionAlias) - { - - ipa.Undo(packageName, actionXml); - } - } - catch (Exception ipaExp) - { - Current.Logger.Error(string.Format("Error undoing package action '{0}' for package {1}", ipa.Alias(), packageName), ipaExp); - } - } - } - - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageInstance.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageInstance.cs deleted file mode 100644 index 736a7c82d1..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageInstance.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; - -using System.Xml; -using System.Xml.XPath; -using System.Collections.Generic; - -namespace umbraco.cms.businesslogic.packager -{ - public class PackageInstance - { - public int Id { get; set; } - - public string RepositoryGuid { get; set; } - - public string PackageGuid { get; set; } - - public bool HasUpdate { get; set; } - - public bool EnableSkins { get; set; } - - public Guid SkinRepoGuid { get; set; } - - public string Name { get; set; } - - public string Url { get; set; } - - public string Folder { get; set; } - - public string PackagePath { get; set; } - - public string Version { get; set; } - - /// - /// The minimum umbraco version that this package requires - /// - public Version UmbracoVersion { get; set; } - - public string Author { get; set; } - - public string AuthorUrl { get; set; } - - public string License { get; set; } - - public string LicenseUrl { get; set; } - - public string Readme { get; set; } - - public bool ContentLoadChildNodes { get; set; } - - public string ContentNodeId { get; set; } - - public List Macros { get; set; } - - public List Languages { get; set; } - - public List DictionaryItems { get; set; } - - public List Templates { get; set; } - - public List Documenttypes { get; set; } - - public List Stylesheets { get; set; } - - public List Files { get; set; } - - public string LoadControl { get; set; } - - public string Actions { get; set; } - - public List DataTypes { get; set; } - - public string IconUrl { get; set; } - - public PackageInstance() - { - SkinRepoGuid = Guid.Empty; - Name = string.Empty; - Url = string.Empty; - Folder = string.Empty; - PackagePath = string.Empty; - Version = string.Empty; - UmbracoVersion = null; - Author = string.Empty; - AuthorUrl = string.Empty; - License = string.Empty; - LicenseUrl = string.Empty; - Readme = string.Empty; - ContentNodeId = string.Empty; - IconUrl = string.Empty; - Macros = new List(); - Languages = new List(); - DictionaryItems = new List(); - Templates = new List(); - Documenttypes = new List(); - Stylesheets = new List(); - Files = new List(); - LoadControl = string.Empty; - DataTypes = new List(); - EnableSkins = false; - ContentLoadChildNodes = false; - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackagerUtility.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackagerUtility.cs deleted file mode 100644 index 81c286a4e6..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackagerUtility.cs +++ /dev/null @@ -1,344 +0,0 @@ -using System; -using System.Data; -using System.Collections; -using System.Collections.Generic; - -using System.Configuration; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.WebControls.WebParts; -using System.Web.UI.HtmlControls; - -using System.IO; -using System.Xml; - -using umbraco.cms.businesslogic.template; -using umbraco.cms.businesslogic.web; -using umbraco.cms.businesslogic.macro; -using ICSharpCode.SharpZipLib.Zip; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.IO; - -namespace umbraco.cms.businesslogic.packager -{ - /// - /// A utillity class for working with packager data. - /// It provides basic methods for adding new items to a package manifest, moving files and other misc. - /// - public class PackagerUtility - { - /// - /// Creates a package manifest containing name, license, version and other meta data. - /// - /// The packinstance. - /// The xml document. - /// - public static XmlNode PackageInfo(PackageInstance pack, XmlDocument doc) - { - XmlNode info = doc.CreateElement("info"); - - //Package info - XmlNode package = doc.CreateElement("package"); - package.AppendChild(CreateNode("name", pack.Name, doc)); - package.AppendChild(CreateNode("version", pack.Version, doc)); - package.AppendChild(CreateNode("iconUrl", pack.IconUrl, doc)); - - XmlNode license = CreateNode("license", pack.License, doc); - license.Attributes.Append(CreateAttribute("url", pack.LicenseUrl, doc)); - package.AppendChild(license); - - package.AppendChild(CreateNode("url", pack.Url, doc)); - - XmlNode requirements = doc.CreateElement("requirements"); - //NOTE: The defaults are 3.0.0 - I'm just leaving that here since that's the way it's been //SD - requirements.AppendChild(CreateNode("major", pack.UmbracoVersion == null ? "3" : pack.UmbracoVersion.Major.ToInvariantString(), doc)); - requirements.AppendChild(CreateNode("minor", pack.UmbracoVersion == null ? "0" : pack.UmbracoVersion.Minor.ToInvariantString(), doc)); - requirements.AppendChild(CreateNode("patch", pack.UmbracoVersion == null ? "0" : pack.UmbracoVersion.Build.ToInvariantString(), doc)); - if (pack.UmbracoVersion != null) - requirements.Attributes.Append(CreateAttribute("type", "strict", doc)); - - package.AppendChild(requirements); - info.AppendChild(package); - - //Author - XmlNode author = CreateNode("author", "", doc); - author.AppendChild(CreateNode("name", pack.Author, doc)); - author.AppendChild(CreateNode("website", pack.AuthorUrl, doc)); - info.AppendChild(author); - - info.AppendChild(CreateNode("readme", "", doc)); - - return info; - } - - - /// - /// Converts an umbraco template to a package xml node - /// - /// The template id. - /// The xml doc. - /// - public static XmlNode Template(int templateId, XmlDocument doc) - { - Template tmpl = new Template(templateId); - - XmlNode template = doc.CreateElement("Template"); - template.AppendChild(CreateNode("Name", tmpl.Text, doc)); - template.AppendChild(CreateNode("Alias", tmpl.Alias, doc)); - - if (tmpl.MasterTemplate != 0) - template.AppendChild(CreateNode("Master", new Template(tmpl.MasterTemplate).Alias, doc)); - - template.AppendChild(CreateNode("Design", "", doc)); - - return template; - } - - /// - /// Converts a umbraco stylesheet to a package xml node - /// - /// The name of the stylesheet. - /// if set to true [incluce properties]. - /// The doc. - /// - public static XmlNode Stylesheet(string name, bool includeProperties, XmlDocument doc) - { - if (doc == null) throw new ArgumentNullException("doc"); - if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); - - var fileService = Current.Services.FileService; - var sts = fileService.GetStylesheetByName(name); - var stylesheet = doc.CreateElement("Stylesheet"); - stylesheet.AppendChild(CreateNode("Name", sts.Alias, doc)); - stylesheet.AppendChild(CreateNode("FileName", sts.Name, doc)); - stylesheet.AppendChild(CreateNode("Content", "", doc)); - if (includeProperties) - { - var properties = doc.CreateElement("Properties"); - foreach (var ssP in sts.Properties) - { - var property = doc.CreateElement("Property"); - property.AppendChild(CreateNode("Name", ssP.Name, doc)); - property.AppendChild(CreateNode("Alias", ssP.Alias, doc)); - property.AppendChild(CreateNode("Value", ssP.Value, doc)); - } - stylesheet.AppendChild(properties); - } - return stylesheet; - } - - /// - /// Converts a macro to a package xml node - /// - /// The macro id. - /// if set to true [append file]. - /// The package directory. - /// The doc. - /// - public static XmlNode Macro(int macroId, bool appendFile, string packageDirectory, XmlDocument doc) - { - Macro mcr = new Macro(macroId); - - if (appendFile) - { - if (!string.IsNullOrEmpty(mcr.Xslt)) - AppendFileToManifest(IOHelper.ResolveUrl(SystemDirectories.Xslt) + "/" + mcr.Xslt, packageDirectory, doc); - - //TODO: Clearly the packager hasn't worked very well for packaging Partial Views to date since there is no logic in here for that - - //if (!string.IsNullOrEmpty(mcr.ScriptingFile)) - // AppendFileToManifest(IOHelper.ResolveUrl(SystemDirectories.MacroScripts) + "/" + mcr.ScriptingFile, packageDirectory, doc); - - if (!string.IsNullOrEmpty(mcr.Type)) - AppendFileToManifest(mcr.Type, packageDirectory, doc); - } - - return mcr.ToXml(doc); - } - - - /// - /// Appends a file to package manifest and copies the file to the correct folder. - /// - /// The path. - /// The package directory. - /// The doc. - public static void AppendFileToManifest(string path, string packageDirectory, XmlDocument doc) - { - if (!path.StartsWith("~/") && !path.StartsWith("/")) - path = "~/" + path; - - string serverPath = IOHelper.MapPath(path); - - if (System.IO.File.Exists(serverPath)) - - AppendFileXml(path, packageDirectory, doc); - else if (System.IO.Directory.Exists(serverPath)) - ProcessDirectory(path, packageDirectory, doc); - } - - - - //Process files in directory and add them to package - private static void ProcessDirectory(string path, string packageDirectory, XmlDocument doc) - { - string serverPath = IOHelper.MapPath(path); - if (System.IO.Directory.Exists(serverPath)) - { - System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(serverPath); - - foreach (System.IO.FileInfo file in di.GetFiles()) - AppendFileXml(path + "/" + file.Name, packageDirectory, doc); - - foreach (System.IO.DirectoryInfo dir in di.GetDirectories()) - ProcessDirectory(path + "/" + dir.Name, packageDirectory, doc); - } - } - - private static void AppendFileXml(string path, string packageDirectory, XmlDocument doc) - { - - string serverPath = IOHelper.MapPath(path); - - string orgPath = path.Substring(0, (path.LastIndexOf('/'))); - string orgName = path.Substring((path.LastIndexOf('/') + 1)); - string newFileName = orgName; - - if (System.IO.File.Exists(packageDirectory + "/" + orgName)) - { - string fileGuid = System.Guid.NewGuid().ToString(); - newFileName = fileGuid + "_" + newFileName; - } - - //Copy file to directory for zipping... - System.IO.File.Copy(serverPath, packageDirectory + "/" + newFileName, true); - - //Append file info to files xml node - XmlNode files = doc.SelectSingleNode("/umbPackage/files"); - - XmlNode file = doc.CreateElement("file"); - file.AppendChild(CreateNode("guid", newFileName, doc)); - file.AppendChild(CreateNode("orgPath", orgPath == "" ? "/" : orgPath, doc)); - file.AppendChild(CreateNode("orgName", orgName, doc)); - - files.AppendChild(file); - } - - /// - /// Determines whether the file is in the package manifest - /// - /// The GUID. - /// The doc. - /// - /// true if [is file in manifest]; otherwise, false. - /// - public static bool IsFileInManifest(string guid, XmlDocument doc) - { - return false; - } - - private static XmlNode CreateNode(string name, string value, XmlDocument doc) - { - var node = doc.CreateElement(name); - node.InnerXml = value; - return node; - } - - private static XmlAttribute CreateAttribute(string name, string value, XmlDocument doc) - { - var attribute = doc.CreateAttribute(name); - attribute.Value = value; - return attribute; - } - - /// - /// Zips the package. - /// - /// The path. - /// The save path. - public static void ZipPackage(string Path, string savePath) - { - string OutPath = savePath; - - ArrayList ar = GenerateFileList(Path); - // generate file list - // find number of chars to remove from orginal file path - int TrimLength = (Directory.GetParent(Path)).ToString().Length; - - TrimLength += 1; - - //remove '\' - FileStream ostream; - - byte[] obuffer; - - ZipOutputStream oZipStream = new ZipOutputStream(System.IO.File.Create(OutPath)); - // create zip stream - - - oZipStream.SetLevel(9); - // 9 = maximum compression level - ZipEntry oZipEntry; - - foreach (string Fil in ar) // for each file, generate a zipentry - { - oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength)); - oZipStream.PutNextEntry(oZipEntry); - - - if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory - { - ostream = File.OpenRead(Fil); - - obuffer = new byte[ostream.Length]; - - // byte buffer - ostream.Read(obuffer, 0, obuffer.Length); - - oZipStream.Write(obuffer, 0, obuffer.Length); - ostream.Close(); - } - } - oZipStream.Finish(); - oZipStream.Close(); - oZipStream.Dispose(); - oZipStream = null; - - oZipEntry = null; - - - ostream = null; - ar.Clear(); - ar = null; - } - - private static ArrayList GenerateFileList(string Dir) - { - ArrayList mid = new ArrayList(); - - bool Empty = true; - - // add each file in directory - foreach (string file in Directory.GetFiles(Dir)) - { - mid.Add(file); - Empty = false; - } - - // if directory is completely empty, add it - if (Empty && Directory.GetDirectories(Dir).Length == 0) - mid.Add(Dir + @"/"); - - // do this recursively - foreach (string dirs in Directory.GetDirectories(Dir)) - { - foreach (object obj in GenerateFileList(dirs)) - mid.Add(obj); - } - return mid; // return file list - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs b/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs deleted file mode 100644 index 145fb7544b..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs +++ /dev/null @@ -1,291 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using System.IO; -using System.Net; -using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; -using Umbraco.Core.IO; -using Umbraco.Core.Models; - -namespace umbraco.cms.businesslogic.packager.repositories -{ - [Obsolete("This should not be used and will be removed in future Umbraco versions")] - public class Repository : DisposableObject - { - public string Guid { get; private set; } - - public string Name { get; private set; } - - public string RepositoryUrl { get; private set; } - - public string WebserviceUrl { get; private set; } - - - public RepositoryWebservice Webservice - { - get - { - var repo = new RepositoryWebservice(WebserviceUrl); - return repo; - } - } - - public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc) - { - - string packageName = package.Name; - string packageGuid = package.PackageGuid; - string description = package.Readme; - string packageFile = package.PackagePath; - - - System.IO.FileStream fs1 = null; - - try - { - - byte[] pack = new byte[0]; - fs1 = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read); - pack = new byte[fs1.Length]; - fs1.Read(pack, 0, (int) fs1.Length); - fs1.Close(); - fs1 = null; - - byte[] thumb = new byte[0]; //todo upload thumbnail... - - return Webservice.SubmitPackage(Guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description); - } - catch (Exception ex) - { - Current.Logger.Error("An error occurred in SubmitPackage", ex); - - return SubmitStatus.Error; - } - } - - public static List getAll() - { - - var repositories = new List(); - - foreach (var r in UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories) - { - var repository = new Repository - { - Guid = r.Id.ToString(), - Name = r.Name - }; - - repository.RepositoryUrl = r.RepositoryUrl; - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + r.WebServiceUrl.Trim('/'); - if (r.HasCustomWebServiceUrl) - { - string wsUrl = r.WebServiceUrl; - - if (wsUrl.Contains("://")) - { - repository.WebserviceUrl = r.WebServiceUrl; - } - else - { - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); - } - } - - repositories.Add(repository); - } - - return repositories; - } - - public static Repository getByGuid(string repositoryGuid) - { - Guid id; - if (System.Guid.TryParse(repositoryGuid, out id) == false) - { - throw new FormatException("The repositoryGuid is not a valid GUID"); - } - - var found = UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories.FirstOrDefault(x => x.Id == id); - if (found == null) - { - return null; - } - - var repository = new Repository - { - Guid = found.Id.ToString(), - Name = found.Name - }; - - repository.RepositoryUrl = found.RepositoryUrl; - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + found.WebServiceUrl.Trim('/'); - - if (found.HasCustomWebServiceUrl) - { - string wsUrl = found.WebServiceUrl; - - if (wsUrl.Contains("://")) - { - repository.WebserviceUrl = found.WebServiceUrl; - } - else - { - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); - } - } - - return repository; - } - - //shortcut method to download pack from repo and place it on the server... - public string fetch(string packageGuid) - { - return fetch(packageGuid, string.Empty); - } - - public string fetch(string packageGuid, int userId) - { - // log - Current.Services.AuditService.Add(AuditType.PackagerInstall, - string.Format("Package {0} fetched from {1}", packageGuid, this.Guid), - userId, -1); - return fetch(packageGuid); - } - - /// - /// Used to get the correct package file from the repo for the current umbraco version - /// - /// - /// - /// - /// - public string GetPackageFile(string packageGuid, int userId, System.Version currentUmbracoVersion) - { - // log - obsolete - //Audit.Add(AuditTypes.PackagerInstall, - // string.Format("Package {0} fetched from {1}", packageGuid, this.Guid), - // userId, -1); - - var fileByteArray = Webservice.GetPackageFile(packageGuid, currentUmbracoVersion.ToString(3)); - - //successfull - if (fileByteArray.Length > 0) - { - // Check for package directory - if (Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)) == false) - Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); - - using (var fs1 = new FileStream(IOHelper.MapPath(Settings.PackagerRoot + Path.DirectorySeparatorChar + packageGuid + ".umb"), FileMode.Create)) - { - fs1.Write(fileByteArray, 0, fileByteArray.Length); - fs1.Close(); - return "packages\\" + packageGuid + ".umb"; - } - } - - return ""; - } - - public bool HasConnection() - { - - string strServer = this.RepositoryUrl; - - try - { - - HttpWebRequest reqFP = (HttpWebRequest) HttpWebRequest.Create(strServer); - HttpWebResponse rspFP = (HttpWebResponse) reqFP.GetResponse(); - - if (HttpStatusCode.OK == rspFP.StatusCode) - { - - // HTTP = 200 - Internet connection available, server online - rspFP.Close(); - - return true; - - } - else - { - - // Other status - Server or connection not available - - rspFP.Close(); - - return false; - - } - - } - catch (WebException) - { - - // Exception - connection not available - - return false; - - } - } - - /// - /// This goes and fetches the Byte array for the package from OUR, but it's pretty strange - /// - /// - /// The package ID for the package file to be returned - /// - /// - /// This is a strange Umbraco version parameter - but it's not really an umbraco version, it's a special/odd version format like Version41 - /// but it's actually not used for the 7.5+ package installs so it's obsolete/unused. - /// - /// - public string fetch(string packageGuid, string key) - { - - byte[] fileByteArray = new byte[0]; - - if (key == string.Empty) - { - fileByteArray = Webservice.fetchPackageByVersion(packageGuid, Version.Version41); - } - else - { - fileByteArray = Webservice.fetchProtectedPackage(packageGuid, key); - } - - //successfull - if (fileByteArray.Length > 0) - { - - // Check for package directory - if (Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)) == false) - Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); - - using (var fs1 = new FileStream(IOHelper.MapPath(Settings.PackagerRoot + Path.DirectorySeparatorChar + packageGuid + ".umb"), FileMode.Create)) - { - fs1.Write(fileByteArray, 0, fileByteArray.Length); - fs1.Close(); - return "packages\\" + packageGuid + ".umb"; - } - } - - // log - - return ""; - } - - /// - /// Handles the disposal of resources. Derived from abstract class which handles common required locking logic. - /// - protected override void DisposeResources() - { - Webservice.Dispose(); - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs b/src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs deleted file mode 100644 index a2da17dd76..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs +++ /dev/null @@ -1,2002 +0,0 @@ -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.Web.Services; -using System.Web.Services.Protocols; -using System.Xml.Serialization; - -namespace umbraco.cms.businesslogic.packager.repositories -{ - - - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Web.Services.WebServiceBindingAttribute(Name = "RepositorySoap", Namespace = "http://packages.umbraco.org/webservices/")] - public partial class RepositoryWebservice : System.Web.Services.Protocols.SoapHttpClientProtocol - { - - private System.Threading.SendOrPostCallback CategoriesOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosByVersionOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosCategorizedOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosCategorizedByVersionOperationCompleted; - - private System.Threading.SendOrPostCallback StarterKitsOperationCompleted; - - private System.Threading.SendOrPostCallback StarterKitModulesCategorizedOperationCompleted; - - private System.Threading.SendOrPostCallback StarterKitModulesOperationCompleted; - - private System.Threading.SendOrPostCallback authenticateOperationCompleted; - - private System.Threading.SendOrPostCallback GetPackageFileOperationCompleted; - - private System.Threading.SendOrPostCallback fetchPackageByVersionOperationCompleted; - - private System.Threading.SendOrPostCallback fetchPackageOperationCompleted; - - private System.Threading.SendOrPostCallback fetchProtectedPackageOperationCompleted; - - private System.Threading.SendOrPostCallback SubmitPackageOperationCompleted; - - private System.Threading.SendOrPostCallback PackageByGuidOperationCompleted; - - private System.Threading.SendOrPostCallback SkinByGuidOperationCompleted; - - private System.Threading.SendOrPostCallback SkinsOperationCompleted; - - /// - public RepositoryWebservice(string url) - { - this.Url = url;//"http://our.umbraco.org/umbraco/webservices/api/repository.asmx"; - } - - /// - public event CategoriesCompletedEventHandler CategoriesCompleted; - - /// - public event NitrosCompletedEventHandler NitrosCompleted; - - /// - public event NitrosByVersionCompletedEventHandler NitrosByVersionCompleted; - - /// - public event NitrosCategorizedCompletedEventHandler NitrosCategorizedCompleted; - - /// - public event NitrosCategorizedByVersionCompletedEventHandler NitrosCategorizedByVersionCompleted; - - /// - public event StarterKitsCompletedEventHandler StarterKitsCompleted; - - /// - public event StarterKitModulesCategorizedCompletedEventHandler StarterKitModulesCategorizedCompleted; - - /// - public event StarterKitModulesCompletedEventHandler StarterKitModulesCompleted; - - /// - public event authenticateCompletedEventHandler authenticateCompleted; - - /// - public event GetPackageFileCompletedEventHandler GetPackageFileCompleted; - - /// - public event fetchPackageByVersionCompletedEventHandler fetchPackageByVersionCompleted; - - /// - public event fetchPackageCompletedEventHandler fetchPackageCompleted; - - /// - public event fetchProtectedPackageCompletedEventHandler fetchProtectedPackageCompleted; - - /// - public event SubmitPackageCompletedEventHandler SubmitPackageCompleted; - - /// - public event PackageByGuidCompletedEventHandler PackageByGuidCompleted; - - /// - public event SkinByGuidCompletedEventHandler SkinByGuidCompleted; - - /// - public event SkinsCompletedEventHandler SkinsCompleted; - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/Categories", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] Categories(string repositoryGuid) - { - object[] results = this.Invoke("Categories", new object[] { - repositoryGuid}); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginCategories(string repositoryGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("Categories", new object[] { - repositoryGuid}, callback, asyncState); - } - - /// - public Category[] EndCategories(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void CategoriesAsync(string repositoryGuid) - { - this.CategoriesAsync(repositoryGuid, null); - } - - /// - public void CategoriesAsync(string repositoryGuid, object userState) - { - if ((this.CategoriesOperationCompleted == null)) - { - this.CategoriesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCategoriesOperationCompleted); - } - this.InvokeAsync("Categories", new object[] { - repositoryGuid}, this.CategoriesOperationCompleted, userState); - } - - private void OnCategoriesOperationCompleted(object arg) - { - if ((this.CategoriesCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.CategoriesCompleted(this, new CategoriesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/Nitros", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] Nitros() - { - object[] results = this.Invoke("Nitros", new object[0]); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitros(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("Nitros", new object[0], callback, asyncState); - } - - /// - public Package[] EndNitros(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void NitrosAsync() - { - this.NitrosAsync(null); - } - - /// - public void NitrosAsync(object userState) - { - if ((this.NitrosOperationCompleted == null)) - { - this.NitrosOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosOperationCompleted); - } - this.InvokeAsync("Nitros", new object[0], this.NitrosOperationCompleted, userState); - } - - private void OnNitrosOperationCompleted(object arg) - { - if ((this.NitrosCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosCompleted(this, new NitrosCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/NitrosByVersion", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] NitrosByVersion(Version version) - { - object[] results = this.Invoke("NitrosByVersion", new object[] { - version}); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitrosByVersion(Version version, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("NitrosByVersion", new object[] { - version}, callback, asyncState); - } - - /// - public Package[] EndNitrosByVersion(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void NitrosByVersionAsync(Version version) - { - this.NitrosByVersionAsync(version, null); - } - - /// - public void NitrosByVersionAsync(Version version, object userState) - { - if ((this.NitrosByVersionOperationCompleted == null)) - { - this.NitrosByVersionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosByVersionOperationCompleted); - } - this.InvokeAsync("NitrosByVersion", new object[] { - version}, this.NitrosByVersionOperationCompleted, userState); - } - - private void OnNitrosByVersionOperationCompleted(object arg) - { - if ((this.NitrosByVersionCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosByVersionCompleted(this, new NitrosByVersionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/NitrosCategorized", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] NitrosCategorized() - { - object[] results = this.Invoke("NitrosCategorized", new object[0]); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitrosCategorized(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("NitrosCategorized", new object[0], callback, asyncState); - } - - /// - public Category[] EndNitrosCategorized(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void NitrosCategorizedAsync() - { - this.NitrosCategorizedAsync(null); - } - - /// - public void NitrosCategorizedAsync(object userState) - { - if ((this.NitrosCategorizedOperationCompleted == null)) - { - this.NitrosCategorizedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosCategorizedOperationCompleted); - } - this.InvokeAsync("NitrosCategorized", new object[0], this.NitrosCategorizedOperationCompleted, userState); - } - - private void OnNitrosCategorizedOperationCompleted(object arg) - { - if ((this.NitrosCategorizedCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosCategorizedCompleted(this, new NitrosCategorizedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/NitrosCategorizedByVersion", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] NitrosCategorizedByVersion(Version version) - { - object[] results = this.Invoke("NitrosCategorizedByVersion", new object[] { - version}); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitrosCategorizedByVersion(Version version, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("NitrosCategorizedByVersion", new object[] { - version}, callback, asyncState); - } - - /// - public Category[] EndNitrosCategorizedByVersion(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void NitrosCategorizedByVersionAsync(Version version) - { - this.NitrosCategorizedByVersionAsync(version, null); - } - - /// - public void NitrosCategorizedByVersionAsync(Version version, object userState) - { - if ((this.NitrosCategorizedByVersionOperationCompleted == null)) - { - this.NitrosCategorizedByVersionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosCategorizedByVersionOperationCompleted); - } - this.InvokeAsync("NitrosCategorizedByVersion", new object[] { - version}, this.NitrosCategorizedByVersionOperationCompleted, userState); - } - - private void OnNitrosCategorizedByVersionOperationCompleted(object arg) - { - if ((this.NitrosCategorizedByVersionCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosCategorizedByVersionCompleted(this, new NitrosCategorizedByVersionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/StarterKits", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] StarterKits() - { - object[] results = this.Invoke("StarterKits", new object[0]); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginStarterKits(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("StarterKits", new object[0], callback, asyncState); - } - - /// - public Package[] EndStarterKits(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void StarterKitsAsync() - { - this.StarterKitsAsync(null); - } - - /// - public void StarterKitsAsync(object userState) - { - if ((this.StarterKitsOperationCompleted == null)) - { - this.StarterKitsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStarterKitsOperationCompleted); - } - this.InvokeAsync("StarterKits", new object[0], this.StarterKitsOperationCompleted, userState); - } - - private void OnStarterKitsOperationCompleted(object arg) - { - if ((this.StarterKitsCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.StarterKitsCompleted(this, new StarterKitsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/StarterKitModulesCategorized", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] StarterKitModulesCategorized() - { - object[] results = this.Invoke("StarterKitModulesCategorized", new object[0]); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginStarterKitModulesCategorized(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("StarterKitModulesCategorized", new object[0], callback, asyncState); - } - - /// - public Category[] EndStarterKitModulesCategorized(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void StarterKitModulesCategorizedAsync() - { - this.StarterKitModulesCategorizedAsync(null); - } - - /// - public void StarterKitModulesCategorizedAsync(object userState) - { - if ((this.StarterKitModulesCategorizedOperationCompleted == null)) - { - this.StarterKitModulesCategorizedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStarterKitModulesCategorizedOperationCompleted); - } - this.InvokeAsync("StarterKitModulesCategorized", new object[0], this.StarterKitModulesCategorizedOperationCompleted, userState); - } - - private void OnStarterKitModulesCategorizedOperationCompleted(object arg) - { - if ((this.StarterKitModulesCategorizedCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.StarterKitModulesCategorizedCompleted(this, new StarterKitModulesCategorizedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/StarterKitModules", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] StarterKitModules() - { - object[] results = this.Invoke("StarterKitModules", new object[0]); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginStarterKitModules(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("StarterKitModules", new object[0], callback, asyncState); - } - - /// - public Package[] EndStarterKitModules(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void StarterKitModulesAsync() - { - this.StarterKitModulesAsync(null); - } - - /// - public void StarterKitModulesAsync(object userState) - { - if ((this.StarterKitModulesOperationCompleted == null)) - { - this.StarterKitModulesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStarterKitModulesOperationCompleted); - } - this.InvokeAsync("StarterKitModules", new object[0], this.StarterKitModulesOperationCompleted, userState); - } - - private void OnStarterKitModulesOperationCompleted(object arg) - { - if ((this.StarterKitModulesCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.StarterKitModulesCompleted(this, new StarterKitModulesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/authenticate", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public string authenticate(string email, string md5Password) - { - object[] results = this.Invoke("authenticate", new object[] { - email, - md5Password}); - return ((string)(results[0])); - } - - /// - public System.IAsyncResult Beginauthenticate(string email, string md5Password, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("authenticate", new object[] { - email, - md5Password}, callback, asyncState); - } - - /// - public string Endauthenticate(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((string)(results[0])); - } - - /// - public void authenticateAsync(string email, string md5Password) - { - this.authenticateAsync(email, md5Password, null); - } - - /// - public void authenticateAsync(string email, string md5Password, object userState) - { - if ((this.authenticateOperationCompleted == null)) - { - this.authenticateOperationCompleted = new System.Threading.SendOrPostCallback(this.OnauthenticateOperationCompleted); - } - this.InvokeAsync("authenticate", new object[] { - email, - md5Password}, this.authenticateOperationCompleted, userState); - } - - private void OnauthenticateOperationCompleted(object arg) - { - if ((this.authenticateCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.authenticateCompleted(this, new authenticateCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - - - - - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/GetPackageFile", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] GetPackageFile(string packageGuid, string umbracoVersion) - { - object[] results = this.Invoke("GetPackageFile", new object[] { - packageGuid, - umbracoVersion}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchPackageByVersion(string packageGuid, string umbracoVersion, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("GetPackageFile", new object[] { - packageGuid, - umbracoVersion}, callback, asyncState); - } - - /// - public byte[] EndGetPackageFile(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void GetPackageFileAsync(string packageGuid, string umbracoVersion) - { - this.GetPackageFileAsync(packageGuid, umbracoVersion, null); - } - - /// - public void GetPackageFileAsync(string packageGuid, string umbracoVersion, object userState) - { - if ((this.GetPackageFileOperationCompleted == null)) - { - this.GetPackageFileOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetPackageFileOperationCompleted); - } - this.InvokeAsync("GetPackageFile", new object[] { - packageGuid, - umbracoVersion}, this.GetPackageFileOperationCompleted, userState); - } - - private void OnGetPackageFileOperationCompleted(object arg) - { - if ((this.GetPackageFileCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.GetPackageFileCompleted(this, new GetPackageFileCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - - - - - - - - - - - - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/fetchPackageByVersion", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] fetchPackageByVersion(string packageGuid, Version schemaVersion) - { - object[] results = this.Invoke("fetchPackageByVersion", new object[] { - packageGuid, - schemaVersion}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchPackageByVersion(string packageGuid, Version schemaVersion, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("fetchPackageByVersion", new object[] { - packageGuid, - schemaVersion}, callback, asyncState); - } - - /// - public byte[] EndfetchPackageByVersion(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void fetchPackageByVersionAsync(string packageGuid, Version schemaVersion) - { - this.fetchPackageByVersionAsync(packageGuid, schemaVersion, null); - } - - /// - public void fetchPackageByVersionAsync(string packageGuid, Version schemaVersion, object userState) - { - if ((this.fetchPackageByVersionOperationCompleted == null)) - { - this.fetchPackageByVersionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnfetchPackageByVersionOperationCompleted); - } - this.InvokeAsync("fetchPackageByVersion", new object[] { - packageGuid, - schemaVersion}, this.fetchPackageByVersionOperationCompleted, userState); - } - - private void OnfetchPackageByVersionOperationCompleted(object arg) - { - if ((this.fetchPackageByVersionCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.fetchPackageByVersionCompleted(this, new fetchPackageByVersionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/fetchPackage", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] fetchPackage(string packageGuid) - { - object[] results = this.Invoke("fetchPackage", new object[] { - packageGuid}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchPackage(string packageGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("fetchPackage", new object[] { - packageGuid}, callback, asyncState); - } - - /// - public byte[] EndfetchPackage(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void fetchPackageAsync(string packageGuid) - { - this.fetchPackageAsync(packageGuid, null); - } - - /// - public void fetchPackageAsync(string packageGuid, object userState) - { - if ((this.fetchPackageOperationCompleted == null)) - { - this.fetchPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnfetchPackageOperationCompleted); - } - this.InvokeAsync("fetchPackage", new object[] { - packageGuid}, this.fetchPackageOperationCompleted, userState); - } - - private void OnfetchPackageOperationCompleted(object arg) - { - if ((this.fetchPackageCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.fetchPackageCompleted(this, new fetchPackageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/fetchProtectedPackage", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] fetchProtectedPackage(string packageGuid, string memberKey) - { - object[] results = this.Invoke("fetchProtectedPackage", new object[] { - packageGuid, - memberKey}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchProtectedPackage(string packageGuid, string memberKey, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("fetchProtectedPackage", new object[] { - packageGuid, - memberKey}, callback, asyncState); - } - - /// - public byte[] EndfetchProtectedPackage(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void fetchProtectedPackageAsync(string packageGuid, string memberKey) - { - this.fetchProtectedPackageAsync(packageGuid, memberKey, null); - } - - /// - public void fetchProtectedPackageAsync(string packageGuid, string memberKey, object userState) - { - if ((this.fetchProtectedPackageOperationCompleted == null)) - { - this.fetchProtectedPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnfetchProtectedPackageOperationCompleted); - } - this.InvokeAsync("fetchProtectedPackage", new object[] { - packageGuid, - memberKey}, this.fetchProtectedPackageOperationCompleted, userState); - } - - private void OnfetchProtectedPackageOperationCompleted(object arg) - { - if ((this.fetchProtectedPackageCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.fetchProtectedPackageCompleted(this, new fetchProtectedPackageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/SubmitPackage", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public SubmitStatus SubmitPackage(string repositoryGuid, string authorGuid, string packageGuid, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] packageFile, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] packageDoc, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] packageThumbnail, string name, string author, string authorUrl, string description) - { - object[] results = this.Invoke("SubmitPackage", new object[] { - repositoryGuid, - authorGuid, - packageGuid, - packageFile, - packageDoc, - packageThumbnail, - name, - author, - authorUrl, - description}); - return ((SubmitStatus)(results[0])); - } - - /// - public System.IAsyncResult BeginSubmitPackage(string repositoryGuid, string authorGuid, string packageGuid, byte[] packageFile, byte[] packageDoc, byte[] packageThumbnail, string name, string author, string authorUrl, string description, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("SubmitPackage", new object[] { - repositoryGuid, - authorGuid, - packageGuid, - packageFile, - packageDoc, - packageThumbnail, - name, - author, - authorUrl, - description}, callback, asyncState); - } - - /// - public SubmitStatus EndSubmitPackage(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((SubmitStatus)(results[0])); - } - - /// - public void SubmitPackageAsync(string repositoryGuid, string authorGuid, string packageGuid, byte[] packageFile, byte[] packageDoc, byte[] packageThumbnail, string name, string author, string authorUrl, string description) - { - this.SubmitPackageAsync(repositoryGuid, authorGuid, packageGuid, packageFile, packageDoc, packageThumbnail, name, author, authorUrl, description, null); - } - - /// - public void SubmitPackageAsync(string repositoryGuid, string authorGuid, string packageGuid, byte[] packageFile, byte[] packageDoc, byte[] packageThumbnail, string name, string author, string authorUrl, string description, object userState) - { - if ((this.SubmitPackageOperationCompleted == null)) - { - this.SubmitPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSubmitPackageOperationCompleted); - } - this.InvokeAsync("SubmitPackage", new object[] { - repositoryGuid, - authorGuid, - packageGuid, - packageFile, - packageDoc, - packageThumbnail, - name, - author, - authorUrl, - description}, this.SubmitPackageOperationCompleted, userState); - } - - private void OnSubmitPackageOperationCompleted(object arg) - { - if ((this.SubmitPackageCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.SubmitPackageCompleted(this, new SubmitPackageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/PackageByGuid", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package PackageByGuid(string packageGuid) - { - object[] results = this.Invoke("PackageByGuid", new object[] { - packageGuid}); - return ((Package)(results[0])); - } - - /// - public System.IAsyncResult BeginPackageByGuid(string packageGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("PackageByGuid", new object[] { - packageGuid}, callback, asyncState); - } - - /// - public Package EndPackageByGuid(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package)(results[0])); - } - - /// - public void PackageByGuidAsync(string packageGuid) - { - this.PackageByGuidAsync(packageGuid, null); - } - - /// - public void PackageByGuidAsync(string packageGuid, object userState) - { - if ((this.PackageByGuidOperationCompleted == null)) - { - this.PackageByGuidOperationCompleted = new System.Threading.SendOrPostCallback(this.OnPackageByGuidOperationCompleted); - } - this.InvokeAsync("PackageByGuid", new object[] { - packageGuid}, this.PackageByGuidOperationCompleted, userState); - } - - private void OnPackageByGuidOperationCompleted(object arg) - { - if ((this.PackageByGuidCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.PackageByGuidCompleted(this, new PackageByGuidCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/SkinByGuid", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Skin SkinByGuid(string skinGuid) - { - object[] results = this.Invoke("SkinByGuid", new object[] { - skinGuid}); - return ((Skin)(results[0])); - } - - /// - public System.IAsyncResult BeginSkinByGuid(string skinGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("SkinByGuid", new object[] { - skinGuid}, callback, asyncState); - } - - /// - public Skin EndSkinByGuid(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Skin)(results[0])); - } - - /// - public void SkinByGuidAsync(string skinGuid) - { - this.SkinByGuidAsync(skinGuid, null); - } - - /// - public void SkinByGuidAsync(string skinGuid, object userState) - { - if ((this.SkinByGuidOperationCompleted == null)) - { - this.SkinByGuidOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSkinByGuidOperationCompleted); - } - this.InvokeAsync("SkinByGuid", new object[] { - skinGuid}, this.SkinByGuidOperationCompleted, userState); - } - - private void OnSkinByGuidOperationCompleted(object arg) - { - if ((this.SkinByGuidCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.SkinByGuidCompleted(this, new SkinByGuidCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/Skins", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Skin[] Skins(string starterKitGuid) - { - object[] results = this.Invoke("Skins", new object[] { - starterKitGuid}); - return ((Skin[])(results[0])); - } - - /// - public System.IAsyncResult BeginSkins(string starterKitGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("Skins", new object[] { - starterKitGuid}, callback, asyncState); - } - - /// - public Skin[] EndSkins(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Skin[])(results[0])); - } - - /// - public void SkinsAsync(string starterKitGuid) - { - this.SkinsAsync(starterKitGuid, null); - } - - /// - public void SkinsAsync(string starterKitGuid, object userState) - { - if ((this.SkinsOperationCompleted == null)) - { - this.SkinsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSkinsOperationCompleted); - } - this.InvokeAsync("Skins", new object[] { - starterKitGuid}, this.SkinsOperationCompleted, userState); - } - - private void OnSkinsOperationCompleted(object arg) - { - if ((this.SkinsCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.SkinsCompleted(this, new SkinsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - public new void CancelAsync(object userState) - { - base.CancelAsync(userState); - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public partial class Category - { - - private string textField; - - private string descriptionField; - - private string urlField; - - private int idField; - - private Package[] packagesField; - - /// - public string Text - { - get - { - return this.textField; - } - set - { - this.textField = value; - } - } - - /// - public string Description - { - get - { - return this.descriptionField; - } - set - { - this.descriptionField = value; - } - } - - /// - public string Url - { - get - { - return this.urlField; - } - set - { - this.urlField = value; - } - } - - /// - public int Id - { - get - { - return this.idField; - } - set - { - this.idField = value; - } - } - - /// - public Package[] Packages - { - get - { - return this.packagesField; - } - set - { - this.packagesField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public partial class Package - { - - private System.Guid repoGuidField; - - private string textField; - - private string descriptionField; - - private string iconField; - - private string thumbnailField; - - private string documentationField; - - private string demoField; - - private bool acceptedField; - - private bool editorsPickField; - - private bool protectedField; - - private bool hasUpgradeField; - - private string upgradeVersionField; - - private string upgradeReadMeField; - - private string urlField; - - /// - public System.Guid RepoGuid - { - get - { - return this.repoGuidField; - } - set - { - this.repoGuidField = value; - } - } - - /// - public string Text - { - get - { - return this.textField; - } - set - { - this.textField = value; - } - } - - /// - public string Description - { - get - { - return this.descriptionField; - } - set - { - this.descriptionField = value; - } - } - - /// - public string Icon - { - get - { - return this.iconField; - } - set - { - this.iconField = value; - } - } - - /// - public string Thumbnail - { - get - { - return this.thumbnailField; - } - set - { - this.thumbnailField = value; - } - } - - /// - public string Documentation - { - get - { - return this.documentationField; - } - set - { - this.documentationField = value; - } - } - - /// - public string Demo - { - get - { - return this.demoField; - } - set - { - this.demoField = value; - } - } - - /// - public bool Accepted - { - get - { - return this.acceptedField; - } - set - { - this.acceptedField = value; - } - } - - /// - public bool EditorsPick - { - get - { - return this.editorsPickField; - } - set - { - this.editorsPickField = value; - } - } - - /// - public bool Protected - { - get - { - return this.protectedField; - } - set - { - this.protectedField = value; - } - } - - /// - public bool HasUpgrade - { - get - { - return this.hasUpgradeField; - } - set - { - this.hasUpgradeField = value; - } - } - - /// - public string UpgradeVersion - { - get - { - return this.upgradeVersionField; - } - set - { - this.upgradeVersionField = value; - } - } - - /// - public string UpgradeReadMe - { - get - { - return this.upgradeReadMeField; - } - set - { - this.upgradeReadMeField = value; - } - } - - /// - public string Url - { - get - { - return this.urlField; - } - set - { - this.urlField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public partial class Skin - { - - private System.Guid repoGuidField; - - private string textField; - - private string thumbnailField; - - private string previewField; - - private string descriptionField; - - private string authorField; - - private string authorUrlField; - - private string licenseField; - - private string licenseUrlField; - - /// - public System.Guid RepoGuid - { - get - { - return this.repoGuidField; - } - set - { - this.repoGuidField = value; - } - } - - /// - public string Text - { - get - { - return this.textField; - } - set - { - this.textField = value; - } - } - - /// - public string Thumbnail - { - get - { - return this.thumbnailField; - } - set - { - this.thumbnailField = value; - } - } - - /// - public string Preview - { - get - { - return this.previewField; - } - set - { - this.previewField = value; - } - } - - /// - public string Description - { - get - { - return this.descriptionField; - } - set - { - this.descriptionField = value; - } - } - - /// - public string Author - { - get - { - return this.authorField; - } - set - { - this.authorField = value; - } - } - - /// - public string AuthorUrl - { - get - { - return this.authorUrlField; - } - set - { - this.authorUrlField = value; - } - } - - /// - public string License - { - get - { - return this.licenseField; - } - set - { - this.licenseField = value; - } - } - - /// - public string LicenseUrl - { - get - { - return this.licenseUrlField; - } - set - { - this.licenseUrlField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public enum Version - { - - /// - Version3, - - /// - Version4, - - /// - /// This is apparently the version number we pass in for all installs - /// - Version41, - - /// - Version41Legacy, - - /// - Version50, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public enum SubmitStatus - { - - /// - Complete, - - /// - Exists, - - /// - NoAccess, - - /// - Error, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void CategoriesCompletedEventHandler(object sender, CategoriesCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class CategoriesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal CategoriesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosCompletedEventHandler(object sender, NitrosCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosByVersionCompletedEventHandler(object sender, NitrosByVersionCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosByVersionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosByVersionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosCategorizedCompletedEventHandler(object sender, NitrosCategorizedCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosCategorizedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosCategorizedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosCategorizedByVersionCompletedEventHandler(object sender, NitrosCategorizedByVersionCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosCategorizedByVersionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosCategorizedByVersionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void StarterKitsCompletedEventHandler(object sender, StarterKitsCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class StarterKitsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal StarterKitsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void StarterKitModulesCategorizedCompletedEventHandler(object sender, StarterKitModulesCategorizedCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class StarterKitModulesCategorizedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal StarterKitModulesCategorizedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void StarterKitModulesCompletedEventHandler(object sender, StarterKitModulesCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class StarterKitModulesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal StarterKitModulesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void authenticateCompletedEventHandler(object sender, authenticateCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class authenticateCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal authenticateCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public string Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((string)(this.results[0])); - } - } - } - - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void GetPackageFileCompletedEventHandler(object sender, GetPackageFileCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class GetPackageFileCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal GetPackageFileCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void fetchPackageByVersionCompletedEventHandler(object sender, fetchPackageByVersionCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class fetchPackageByVersionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal fetchPackageByVersionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void fetchPackageCompletedEventHandler(object sender, fetchPackageCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class fetchPackageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal fetchPackageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void fetchProtectedPackageCompletedEventHandler(object sender, fetchProtectedPackageCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class fetchProtectedPackageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal fetchProtectedPackageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void SubmitPackageCompletedEventHandler(object sender, SubmitPackageCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class SubmitPackageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal SubmitPackageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public SubmitStatus Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((SubmitStatus)(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void PackageByGuidCompletedEventHandler(object sender, PackageByGuidCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class PackageByGuidCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal PackageByGuidCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package)(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void SkinByGuidCompletedEventHandler(object sender, SkinByGuidCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class SkinByGuidCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal SkinByGuidCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Skin Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Skin)(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void SkinsCompletedEventHandler(object sender, SkinsCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class SkinsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal SkinsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Skin[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Skin[])(this.results[0])); - } - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/RequirementsType.cs b/src/umbraco.cms/businesslogic/Packager/RequirementsType.cs deleted file mode 100644 index 73022cda50..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/RequirementsType.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace umbraco.cms.businesslogic.packager -{ - public enum RequirementsType - { - Strict, - Legacy - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/Packager/Settings.cs b/src/umbraco.cms/businesslogic/Packager/Settings.cs deleted file mode 100644 index e8136fc95e..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/Settings.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Data; -using System.Configuration; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.WebControls.WebParts; -using System.Web.UI.HtmlControls; -using System.IO; -using Umbraco.Core.IO; - -namespace umbraco.cms.businesslogic.packager -{ - public class Settings - { - - public static string PackagerRoot - { - get { return SystemDirectories.Packages; } - } - - public static string PackagesStorage - { - get { return SystemDirectories.Packages + IOHelper.DirSepChar + "created"; } - } - - public static string InstalledPackagesStorage - { - get { return SystemDirectories.Packages + IOHelper.DirSepChar + "installed"; } - } - - public static string InstalledPackagesSettings - { - get { return SystemDirectories.Packages + IOHelper.DirSepChar + "installed" + IOHelper.DirSepChar + "installedPackages.config"; } - } - - public static string CreatedPackagesSettings - { - get { return SystemDirectories.Packages + IOHelper.DirSepChar + "created" + IOHelper.DirSepChar + "createdPackages.config"; } - } - - public static string PackageFileExtension - { - get { return "zip"; } - } - - public static bool HasFileAccess(ref Exception exp) - { - bool hasAccess = false; - StreamWriter sw1 = null; - StreamWriter sw2 = null; - try - { - sw1 = System.IO.File.AppendText(IOHelper.MapPath(InstalledPackagesSettings)); - sw1.Close(); - - sw2 = System.IO.File.AppendText(IOHelper.MapPath(CreatedPackagesSettings)); - sw1.Close(); - - System.IO.Directory.CreateDirectory(IOHelper.MapPath(PackagesStorage) + IOHelper.DirSepChar + "__testFolder__"); - System.IO.Directory.CreateDirectory(IOHelper.MapPath(InstalledPackagesStorage) + IOHelper.DirSepChar + "__testFolder__"); - - System.IO.Directory.Delete(IOHelper.MapPath(PackagesStorage) + IOHelper.DirSepChar + "__testFolder__", true); - System.IO.Directory.Delete(IOHelper.MapPath(InstalledPackagesStorage) + IOHelper.DirSepChar + "__testFolder__", true); - - hasAccess = true; - } - finally - { - if (sw1 != null) - sw1.Close(); - if (sw2 != null) - sw2.Close(); - } - - return hasAccess; - } - - - } - -} diff --git a/src/umbraco.cms/businesslogic/Packager/data.cs b/src/umbraco.cms/businesslogic/Packager/data.cs deleted file mode 100644 index 8612e02310..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/data.cs +++ /dev/null @@ -1,415 +0,0 @@ -using System; -using System.Xml; -using System.Xml.XPath; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; -using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.Composing; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Xml; - -namespace umbraco.cms.businesslogic.packager -{ - /// - /// This is the xml data for installed packages. This is not the same xml as a pckage format! - /// - public class data - { - private static XmlDocument _source; - - public static XmlDocument Source - { - get - { - return _source; - } - } - - public static void Reload(string dataSource) - { - //do some error checking and create the folders/files if they don't exist - if (!File.Exists(dataSource)) - { - if (!Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot))) - { - Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); - } - if (!Directory.Exists(IOHelper.MapPath(Settings.PackagesStorage))) - { - Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagesStorage)); - } - if (!Directory.Exists(IOHelper.MapPath(Settings.InstalledPackagesStorage))) - { - Directory.CreateDirectory(IOHelper.MapPath(Settings.InstalledPackagesStorage)); - } - - using (StreamWriter sw = File.CreateText(dataSource)) - { - sw.Write(umbraco.cms.businesslogic.Packager.FileResources.PackageFiles.Packages); - sw.Flush(); - } - - } - - if (_source == null) - { - _source = new XmlDocument(); - } - - //error checking here - if (File.Exists(dataSource)) - { - var isEmpty = false; - using (var sr = new StreamReader(dataSource)) - { - if (sr.ReadToEnd().IsNullOrWhiteSpace()) - { - isEmpty = true; - } - } - if (isEmpty) - { - File.WriteAllText(dataSource, @""); - } - } - - _source.Load(dataSource); - } - - public static XmlNode GetFromId(int Id, string dataSource, bool reload) - { - if (reload) - Reload(dataSource); - - return Source.SelectSingleNode("/packages/package [@id = '" + Id.ToString().ToUpper() + "']"); - } - - public static XmlNode GetFromGuid(string guid, string dataSource, bool reload) - { - if (reload) - Reload(dataSource); - - return Source.SelectSingleNode("/packages/package [@packageGuid = '" + guid + "']"); - } - - public static PackageInstance MakeNew(string Name, string dataSource) - { - Reload(dataSource); - - int maxId = 1; - // Find max id - foreach (XmlNode n in Source.SelectNodes("packages/package")) - { - if (int.Parse(n.Attributes.GetNamedItem("id").Value) >= maxId) - maxId = int.Parse(n.Attributes.GetNamedItem("id").Value) + 1; - } - - XmlElement instance = Source.CreateElement("package"); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "id", maxId.ToString())); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "version", "")); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "url", "")); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "name", Name)); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "folder", Guid.NewGuid().ToString())); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "packagepath", "")); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "repositoryGuid", "")); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "iconUrl", "")); - //set to current version - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "umbVersion", UmbracoVersion.Current.ToString(3))); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "packageGuid", Guid.NewGuid().ToString())); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "hasUpdate", "false")); - - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "enableSkins", "false")); - instance.Attributes.Append(XmlHelper.AddAttribute(Source, "skinRepoGuid", "")); - - XmlElement license = Source.CreateElement("license"); - license.InnerText = "MIT License"; - license.Attributes.Append(XmlHelper.AddAttribute(Source, "url", "http://opensource.org/licenses/MIT")); - instance.AppendChild(license); - - XmlElement author = Source.CreateElement("author"); - author.InnerText = ""; - author.Attributes.Append(XmlHelper.AddAttribute(Source, "url", "")); - instance.AppendChild(author); - - instance.AppendChild(XmlHelper.AddTextNode(Source, "readme", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "actions", "")); - - instance.AppendChild(XmlHelper.AddTextNode(Source, "datatypes", "")); - - XmlElement content = Source.CreateElement("content"); - content.InnerText = ""; - content.Attributes.Append(XmlHelper.AddAttribute(Source, "nodeId", "")); - content.Attributes.Append(XmlHelper.AddAttribute(Source, "loadChildNodes", "false")); - instance.AppendChild(content); - - instance.AppendChild(XmlHelper.AddTextNode(Source, "templates", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "stylesheets", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "documenttypes", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "macros", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "files", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "languages", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "dictionaryitems", "")); - instance.AppendChild(XmlHelper.AddTextNode(Source, "loadcontrol", "")); - - Source.SelectSingleNode("packages").AppendChild(instance); - Source.Save(dataSource); - var retVal = data.Package(maxId, dataSource); - - return retVal; - } - - public static PackageInstance Package(int id, string datasource) - { - return ConvertXmlToPackage(GetFromId(id, datasource, true)); - } - - public static PackageInstance Package(string guid, string datasource) - { - XmlNode node = GetFromGuid(guid, datasource, true); - if (node != null) - return ConvertXmlToPackage(node); - else - return new PackageInstance(); - } - - public static List GetAllPackages(string dataSource) - { - Reload(dataSource); - XmlNodeList nList = data.Source.SelectNodes("packages/package"); - - List retVal = new List(); - - for (int i = 0; i < nList.Count; i++) - { - try - { - retVal.Add(ConvertXmlToPackage(nList[i])); - } - catch (Exception ex) - { - Current.Logger.Error("An error occurred in GetAllPackages", ex); - } - } - - return retVal; - } - - private static PackageInstance ConvertXmlToPackage(XmlNode n) - { - PackageInstance retVal = new PackageInstance(); - - if (n != null) - { - retVal.Id = int.Parse(SafeAttribute("id", n)); - retVal.Name = SafeAttribute("name", n); - retVal.Folder = SafeAttribute("folder", n); - retVal.PackagePath = SafeAttribute("packagepath", n); - retVal.Version = SafeAttribute("version", n); - retVal.Url = SafeAttribute("url", n); - retVal.RepositoryGuid = SafeAttribute("repositoryGuid", n); - retVal.PackageGuid = SafeAttribute("packageGuid", n); - retVal.HasUpdate = bool.Parse(SafeAttribute("hasUpdate", n)); - - retVal.IconUrl = SafeAttribute("iconUrl", n); - var umbVersion = SafeAttribute("umbVersion", n); - Version parsedVersion; - if (umbVersion.IsNullOrWhiteSpace() == false && Version.TryParse(umbVersion, out parsedVersion)) - { - retVal.UmbracoVersion = parsedVersion; - } - - bool enableSkins = false; - bool.TryParse(SafeAttribute("enableSkins", n), out enableSkins); - retVal.EnableSkins = enableSkins; - - retVal.SkinRepoGuid = string.IsNullOrEmpty(SafeAttribute("skinRepoGuid", n)) ? Guid.Empty : new Guid(SafeAttribute("skinRepoGuid", n)); - - retVal.License = SafeNodeValue(n.SelectSingleNode("license")); - retVal.LicenseUrl = n.SelectSingleNode("license").Attributes.GetNamedItem("url").Value; - - retVal.Author = SafeNodeValue(n.SelectSingleNode("author")); - retVal.AuthorUrl = SafeAttribute("url", n.SelectSingleNode("author")); - - retVal.Readme = SafeNodeValue(n.SelectSingleNode("readme")); - retVal.Actions = SafeNodeInnerXml(n.SelectSingleNode("actions")); - - retVal.ContentNodeId = SafeAttribute("nodeId", n.SelectSingleNode("content")); - retVal.ContentLoadChildNodes = bool.Parse(SafeAttribute("loadChildNodes", n.SelectSingleNode("content"))); - - retVal.Macros = new List(SafeNodeValue(n.SelectSingleNode("macros")).Trim(',').Split(',')); - retVal.Macros = new List(SafeNodeValue(n.SelectSingleNode("macros")).Trim(',').Split(',')); - retVal.Templates = new List(SafeNodeValue(n.SelectSingleNode("templates")).Trim(',').Split(',')); - retVal.Stylesheets = new List(SafeNodeValue(n.SelectSingleNode("stylesheets")).Trim(',').Split(',')); - retVal.Documenttypes = new List(SafeNodeValue(n.SelectSingleNode("documenttypes")).Trim(',').Split(',')); - retVal.Languages = new List(SafeNodeValue(n.SelectSingleNode("languages")).Trim(',').Split(',')); - retVal.DictionaryItems = new List(SafeNodeValue(n.SelectSingleNode("dictionaryitems")).Trim(',').Split(',')); - retVal.DataTypes = new List(SafeNodeValue(n.SelectSingleNode("datatypes")).Trim(',').Split(',')); - - XmlNodeList xmlFiles = n.SelectNodes("files/file"); - retVal.Files = new List(); - - for (int i = 0; i < xmlFiles.Count; i++) - retVal.Files.Add(xmlFiles[i].InnerText); - - retVal.LoadControl = SafeNodeValue(n.SelectSingleNode("loadcontrol")); - } - - return retVal; - } - - public static void Delete(int Id, string dataSource) - { - Reload(dataSource); - // Remove physical xml file if any - //PackageInstance p = new PackageInstance(Id); - - //TODO DELETE PACKAGE FOLDER... - //p.Folder - - XmlNode n = data.GetFromId(Id, dataSource, true); - if (n != null) - { - data.Source.SelectSingleNode("/packages").RemoveChild(n); - data.Source.Save(dataSource); - } - - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is no longer in use and will be removed in the future")] - public static void UpdateValue(XmlNode n, string Value) - { - if (n.FirstChild != null) - n.FirstChild.Value = Value; - else - { - n.AppendChild(Source.CreateTextNode(Value)); - } - } - - public static void Save(PackageInstance package, string dataSource) - { - Reload(dataSource); - var xmlDef = GetFromId(package.Id, dataSource, false); - XmlHelper.SetAttribute(Source, xmlDef, "name", package.Name); - XmlHelper.SetAttribute(Source, xmlDef, "version", package.Version); - XmlHelper.SetAttribute(Source, xmlDef, "url", package.Url); - XmlHelper.SetAttribute(Source, xmlDef, "packagepath", package.PackagePath); - XmlHelper.SetAttribute(Source, xmlDef, "repositoryGuid", package.RepositoryGuid); - XmlHelper.SetAttribute(Source, xmlDef, "packageGuid", package.PackageGuid); - XmlHelper.SetAttribute(Source, xmlDef, "hasUpdate", package.HasUpdate.ToString()); - XmlHelper.SetAttribute(Source, xmlDef, "enableSkins", package.EnableSkins.ToString()); - XmlHelper.SetAttribute(Source, xmlDef, "skinRepoGuid", package.SkinRepoGuid.ToString()); - XmlHelper.SetAttribute(Source, xmlDef, "iconUrl", package.IconUrl); - if (package.UmbracoVersion != null) - XmlHelper.SetAttribute(Source, xmlDef, "umbVersion", package.UmbracoVersion.ToString(3)); - - var licenseNode = xmlDef.SelectSingleNode("license"); - if (licenseNode == null) - { - licenseNode = Source.CreateElement("license"); - xmlDef.AppendChild(licenseNode); - } - licenseNode.InnerText = package.License; - XmlHelper.SetAttribute(Source, licenseNode, "url", package.LicenseUrl); - - var authorNode = xmlDef.SelectSingleNode("author"); - if (authorNode == null) - { - authorNode = Source.CreateElement("author"); - xmlDef.AppendChild(authorNode); - } - authorNode.InnerText = package.Author; - XmlHelper.SetAttribute(Source, authorNode, "url", package.AuthorUrl); - - XmlHelper.SetCDataNode(Source, xmlDef, "readme", package.Readme); - XmlHelper.SetInnerXmlNode(Source, xmlDef, "actions", package.Actions); - - var contentNode = xmlDef.SelectSingleNode("content"); - if (contentNode == null) - { - contentNode = Source.CreateElement("content"); - xmlDef.AppendChild(contentNode); - } - XmlHelper.SetAttribute(Source, contentNode, "nodeId", package.ContentNodeId); - XmlHelper.SetAttribute(Source, contentNode, "loadChildNodes", package.ContentLoadChildNodes.ToString()); - - XmlHelper.SetTextNode(Source, xmlDef, "macros", JoinList(package.Macros, ',')); - XmlHelper.SetTextNode(Source, xmlDef, "templates", JoinList(package.Templates, ',')); - XmlHelper.SetTextNode(Source, xmlDef, "stylesheets", JoinList(package.Stylesheets, ',')); - XmlHelper.SetTextNode(Source, xmlDef, "documenttypes", JoinList(package.Documenttypes, ',')); - XmlHelper.SetTextNode(Source, xmlDef, "languages", JoinList(package.Languages, ',')); - XmlHelper.SetTextNode(Source, xmlDef, "dictionaryitems", JoinList(package.DictionaryItems, ',')); - XmlHelper.SetTextNode(Source, xmlDef, "datatypes", JoinList(package.DataTypes, ',')); - - var filesNode = xmlDef.SelectSingleNode("files"); - if (filesNode == null) - { - filesNode = Source.CreateElement("files"); - xmlDef.AppendChild(filesNode); - } - filesNode.InnerXml = ""; - - foreach (var fileStr in package.Files) - { - if (string.IsNullOrWhiteSpace(fileStr) == false) - filesNode.AppendChild(XmlHelper.AddTextNode(Source, "file", fileStr)); - } - - XmlHelper.SetTextNode(Source, xmlDef, "loadcontrol", package.LoadControl); - - Source.Save(dataSource); - } - - - - private static string SafeAttribute(string name, XmlNode n) - { - return n.Attributes == null || n.Attributes[name] == null ? string.Empty : n.Attributes[name].Value; - } - - private static string SafeNodeValue(XmlNode n) - { - try - { - return XmlHelper.GetNodeValue(n); - } - catch - { - return string.Empty; - } - } - - private static string SafeNodeInnerXml(XmlNode n) - { - try - { - return n.InnerXml; - } - catch - { - return string.Empty; - } - } - - - private static string JoinList(List list, char seperator) - { - string retVal = ""; - foreach (string str in list) - { - retVal += str + seperator; - } - - return retVal.Trim(seperator); - } - - public data() - { - - } - } -} diff --git a/src/umbraco.cms/businesslogic/Permission.cs b/src/umbraco.cms/businesslogic/Permission.cs deleted file mode 100644 index b4eb33673a..0000000000 --- a/src/umbraco.cms/businesslogic/Permission.cs +++ /dev/null @@ -1,176 +0,0 @@ -using System.Linq; -using Umbraco.Core; -using Umbraco.Core.Events; -using umbraco.cms.businesslogic; -using System.Collections.Generic; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Services; - -namespace umbraco.BusinessLogic -{ - /// - /// Summary description for Permission. - /// - public class Permission - { - - public int NodeId { get; private set; } - public int UserId { get; private set; } - public char PermissionId { get; private set; } - - /// - /// Private constructor, this class cannot be directly instantiated - /// - private Permission() { } - - public static void MakeNew(IUser User, CMSNode Node, char PermissionKey) - { - MakeNew(User, new[] { Node }, PermissionKey); - } - - private static void MakeNew(IUser user, IEnumerable nodes, char permissionKey) - { - var asArray = nodes.ToArray(); - - Current.Services.UserService.AssignUserPermission(user.Id, permissionKey, asArray.Select(x => x.Id).ToArray()); - - } - - /// - /// Returns the permissions for a user - /// - /// - /// - public static IEnumerable GetUserPermissions(IUser user) - { - var permissions = Current.Services.UserService.GetPermissions(user); - - return permissions.SelectMany( - entityPermission => entityPermission.AssignedPermissions, - (entityPermission, assignedPermission) => new Permission - { - NodeId = entityPermission.EntityId, - PermissionId = assignedPermission[0], - UserId = entityPermission.UserId - }); - - } - - /// - /// Returns the permissions for a node - /// - /// - /// - public static IEnumerable GetNodePermissions(CMSNode node) - { - var content = Current.Services.ContentService.GetById(node.Id); - if (content == null) return Enumerable.Empty(); - - var permissions = Current.Services.ContentService.GetPermissionsForEntity(content); - - return permissions.SelectMany( - entityPermission => entityPermission.AssignedPermissions, - (entityPermission, assignedPermission) => new Permission - { - NodeId = entityPermission.EntityId, - PermissionId = assignedPermission[0], - UserId = entityPermission.UserId - }); - } - - /// - /// Delets all permissions for the node/user combination - /// - /// - /// - public static void DeletePermissions(IUser user, CMSNode node) - { - Current.Services.UserService.RemoveUserPermissions(user.Id, node.Id); - } - - /// - /// deletes all permissions for the user - /// - /// - public static void DeletePermissions(IUser user) - { - Current.Services.UserService.RemoveUserPermissions(user.Id); - - } - - public static void DeletePermissions(int iUserID, int[] iNodeIDs) - { - Current.Services.UserService.RemoveUserPermissions(iUserID, iNodeIDs); - - } - public static void DeletePermissions(int iUserID, int iNodeID) - { - DeletePermissions(iUserID, new[] { iNodeID }); - } - - /// - /// delete all permissions for this node - /// - /// - public static void DeletePermissions(CMSNode node) - { - Current.Services.ContentService.RemoveContentPermissions(node.Id); - - } - - public static void UpdateCruds(IUser user, CMSNode node, string permissions) - { - Current.Services.UserService.ReplaceUserPermissions( - user.Id, - permissions.ToCharArray(), - node.Id); - - } - - - - } - - internal class UserPermission - { - private int? _userId; - private readonly int[] _nodeIds; - - internal int UserId - { - get - { - if (_userId.HasValue) - { - return _userId.Value; - } - if (User != null) - { - return User.Id; - } - return -1; - } - } - - internal IEnumerable NodeIds - { - get - { - if (_nodeIds != null) - { - return _nodeIds; - } - if (Nodes != null) - { - return Nodes.Select(x => x.Id); - } - return Enumerable.Empty(); - } - } - - internal IUser User { get; private set; } - internal IEnumerable Nodes { get; private set; } - internal char[] PermissionKeys { get; private set; } - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/language/Item.cs b/src/umbraco.cms/businesslogic/language/Item.cs deleted file mode 100644 index afa7659499..0000000000 --- a/src/umbraco.cms/businesslogic/language/Item.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Concurrent; -using System.ComponentModel; -using System.Data; -using System.Linq; - -using Umbraco.Core; -using Umbraco.Core.Models; -using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.SqlSyntax; -using umbraco.DataLayer; -using umbraco.BusinessLogic; -using System.Collections.Generic; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Rdbms; - -namespace umbraco.cms.businesslogic.language -{ - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class is no longer used, nor should it ever be used, it will be removed from the codebase in future versions")] - public class Item - { - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - - /// - /// Retrieves the value of a languagetranslated item given the key - /// - /// Unique identifier - /// Umbraco languageid - /// The language translated text - public static string Text(Guid key, int languageId) - { - - var item = Current.Services.LocalizationService.GetDictionaryItemById(key); - if (item != null) - { - var translation = item.Translations.FirstOrDefault(x => x.Language.Id == languageId); - if (translation != null) - { - return translation.Value; - } - } - - throw new ArgumentException("Key being requested does not exist"); - } - - /// - /// returns True if there is a value associated to the unique identifier with the specified language - /// - /// Unique identifier - /// Umbraco language id - /// returns True if there is a value associated to the unique identifier with the specified language - public static bool hasText(Guid key, int languageId) - { - try - { - return Text(key, languageId).IsNullOrWhiteSpace() == false; - } - catch (ArgumentException) - { - return false; - } - } - - /// - /// Updates the value of the language translated item, throws an exeption if the - /// key does not exist - /// - /// Umbraco language id - /// Unique identifier - /// The new dictionaryvalue - - public static void setText(int languageId, Guid key, string value) - { - var lang = Current.Services.LocalizationService.GetLanguageById(languageId); - if (lang == null) return; - - var item = Current.Services.LocalizationService.GetDictionaryItemById(key); - if (item != null) - { - var translation = item.Translations.FirstOrDefault(x => x.Language.Id == languageId); - if (translation == null) - { - throw new ArgumentException("Key does not exist"); - } - var newTranslations = new List(item.Translations) - { - new DictionaryTranslation(lang, value) - }; - item.Translations = newTranslations; - Current.Services.LocalizationService.Save(item); - } - } - - /// - /// Adds a new languagetranslated item to the collection - /// - /// - /// Umbraco languageid - /// Unique identifier - /// - public static void addText(int languageId, Guid key, string value) - { - var lang = Current.Services.LocalizationService.GetLanguageById(languageId); - if (lang == null) return; - - var item = Current.Services.LocalizationService.GetDictionaryItemById(key); - if (item != null) - { - var translation = item.Translations.FirstOrDefault(x => x.Language.Id == languageId); - if (translation != null) - { - throw new ArgumentException("Key being add'ed already exists"); - } - var newTranslations = new List(item.Translations) - { - new DictionaryTranslation(lang, value) - }; - item.Translations = newTranslations; - Current.Services.LocalizationService.Save(item); - } - } - - /// - /// Removes all languagetranslated texts associated to the unique identifier. - /// - /// Unique identifier - public static void removeText(Guid key) - { - var found = Current.Services.LocalizationService.GetDictionaryItemById(key); - if (found != null) - { - Current.Services.LocalizationService.Delete(found); - } - } - - /// - /// Removes all entries by language id. - /// Primary used when deleting a language from Umbraco. - /// - /// - [Obsolete("This is no longer used and will be removed from the codebase in future versions")] - public static void RemoveByLanguage(int languageId) - { - var lang = Current.Services.LocalizationService.GetLanguageById(languageId); - if (lang != null) - { - Current.Services.LocalizationService.Delete(lang); - } - } - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/language/Language.cs b/src/umbraco.cms/businesslogic/language/Language.cs deleted file mode 100644 index 415063bf48..0000000000 --- a/src/umbraco.cms/businesslogic/language/Language.cs +++ /dev/null @@ -1,274 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Xml; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Models.Rdbms; -using Umbraco.Core.Services; -using umbraco.DataLayer; -using umbraco.BusinessLogic; -using System.Linq; -using Umbraco.Core.Composing; - -namespace umbraco.cms.businesslogic.language -{ - /// - /// The language class contains methods for creating and modifing installed languages. - /// - /// A language is used internal in the umbraco console for displaying languagespecific text and - /// in the public website for language/country specific representation of ex. date/time, currencies. - /// - /// Besides by using the built in Dictionary you are able to store language specific bits and pieces of translated text - /// for use in templates. - /// - [Obsolete("Use the LocalizationService instead")] - public class Language - { - #region Private members - - internal ILanguage LanguageEntity { get; private set; } - - #endregion - - #region Constants and static members - - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The id. - public Language(int id) - { - LanguageEntity = Current.Services.LocalizationService.GetLanguageById(id); - if (LanguageEntity == null) - { - throw new ArgumentException("No language found with the specified id"); - } - } - - /// - /// Empty constructor used to create a language object manually - /// - internal Language() { } - - internal Language(ILanguage langEntity) - { - LanguageEntity = langEntity; - } - - #endregion - - #region Static methods - - /// - /// Creates a new language given the culture code - ie. da-dk (denmark) - /// - /// Culturecode of the language - public static void MakeNew(string cultureCode) - { - var culture = GetCulture(cultureCode); - if (culture != null) - { - //insert it - var lang = new Umbraco.Core.Models.Language(cultureCode) - { - CultureName = culture.DisplayName - }; - Current.Services.LocalizationService.Save(lang); - } - } - - /// - /// Method for accessing all installed languagess - /// - [Obsolete("Use the GetAllAsList() method instead")] - public static Language[] getAll - { - get - { - return GetAllAsList().ToArray(); - } - } - - /// - /// Returns all installed languages - /// - /// - /// - /// This will return a cached set of all languages. if the cache is not found it will create it. - /// - public static IEnumerable GetAllAsList() - { - var all = Current.Services.LocalizationService.GetAllLanguages().Select(x => new Language(x)).ToArray(); - return all; - } - - - /// - /// Gets the language by its culture code, if no language is found, null is returned - /// - /// The culture code. - /// - public static Language GetByCultureCode(string cultureCode) - { - var found = Current.Services.LocalizationService.GetLanguageByIsoCode(cultureCode); - if (found == null) return null; - var lang = new Language(found); - return lang; - } - - private static CultureInfo GetCulture(string cultureCode) - { - try - { - var culture = new CultureInfo(cultureCode); - return culture; - } - catch (Exception ex) - { - Current.Logger.Error("Could not find the culture " + cultureCode, ex); - return null; - } - } - - /// - /// Imports a language from XML - /// - /// The XML data. - /// - [Obsolete("This is no longer used and will be removed in future versions")] - public static Language Import(XmlNode xmlData) - { - var cA = xmlData.Attributes["CultureAlias"].Value; - if (GetByCultureCode(cA) == null) - { - MakeNew(cA); - return GetByCultureCode(cA); - } - return null; - } - - #endregion - - #region Public Properties - /// - /// The id used by umbraco to identify the language - /// - public int id - { - get { return LanguageEntity.Id; } - } - - /// - /// The culture code of the language: ie. Danish/Denmark da-dk - /// - public string CultureAlias - { - get { return LanguageEntity.IsoCode; } - set - { - LanguageEntity.IsoCode = value; - } - } - - /// - /// The user friendly name of the language/country - /// - public string FriendlyName - { - get { return LanguageEntity.CultureInfo.DisplayName; } - } - #endregion - - #region Public methods - - /// - /// Ensures uniqueness by id - /// - /// - /// - public override bool Equals(object obj) - { - var l = obj as Language; - if (l != null) - { - return id.Equals(l.id); - } - return false; - } - - /// - /// Ensures uniqueness by id - /// - /// - public override int GetHashCode() - { - return id.GetHashCode(); - } - - /// - /// Used to persist object changes to the database - /// - public virtual void Save() - { - //Do the update! - Current.Services.LocalizationService.Save(LanguageEntity); - } - - /// - /// Deletes the current Language. - /// - /// Notice: this can have various sideeffects - use with care. - /// - /// - /// You cannot delete the default language: en-US, this is installed by default and is required. - /// - public void Delete() - { - using (var scope = Current.ScopeProvider.CreateScope()) - { - if (scope.Database.ExecuteScalar("SELECT count(id) FROM umbracoDomains where domainDefaultLanguage = @id", new { id = id }) == 0) - { - Current.Services.LocalizationService.Delete(LanguageEntity); - scope.Complete(); - } - else - { - var e = new DataException("Cannot remove language " + LanguageEntity.CultureInfo.DisplayName + " because it's attached to a domain on a node"); - Current.Logger.Error("Cannot remove language " + LanguageEntity.CultureInfo.DisplayName + " because it's attached to a domain on a node", e); - throw e; - } - } - } - - /// - /// Converts the instance to XML - /// - /// The xml document. - /// - public XmlNode ToXml(XmlDocument xd) - { - var serializer = new EntityXmlSerializer(); - var xml = serializer.Serialize(LanguageEntity); - return xml.GetXmlNode(xd); - } - #endregion - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/macro/Macro.cs b/src/umbraco.cms/businesslogic/macro/Macro.cs deleted file mode 100644 index baa034c725..0000000000 --- a/src/umbraco.cms/businesslogic/macro/Macro.cs +++ /dev/null @@ -1,426 +0,0 @@ -using System; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Services; -using umbraco.DataLayer; -using umbraco.BusinessLogic; -using System.Linq; -using Umbraco.Core.Composing; -using Umbraco.Core.Xml; - -namespace umbraco.cms.businesslogic.macro -{ - /// - /// The Macro component are one of the umbraco essentials, used for drawing dynamic content in the public website of umbraco. - /// - /// A Macro is a placeholder for either a xsl transformation, a custom .net control or a .net usercontrol. - /// - /// The Macro is representated in templates and content as a special html element, which are being parsed out and replaced with the - /// output of either the .net control or the xsl transformation when a page is being displayed to the visitor. - /// - /// A macro can have a variety of properties which are used to transfer userinput to either the usercontrol/custom control or the xsl - /// - /// - [Obsolete("This is no longer used, use the IMacroService and related models instead")] - public class Macro - { - //initialize empty model - internal IMacro MacroEntity = new Umbraco.Core.Models.Macro(); - - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper => LegacySqlHelper.SqlHelper; - - /// - /// id - /// - public int Id => MacroEntity.Id; - - /// - /// key - /// - public Guid Key => MacroEntity.Key; - - /// - /// If set to true, the macro can be inserted on documents using the richtexteditor. - /// - public bool UseInEditor - { - get => MacroEntity.UseInEditor; - set => MacroEntity.UseInEditor = value; - } - - /// - /// The cache refreshrate - the maximum amount of time the macro should remain cached in the umbraco - /// runtime layer. - /// - /// The macro caches are refreshed whenever a document is changed - /// - public int RefreshRate - { - get { return MacroEntity.CacheDuration; } - set { MacroEntity.CacheDuration = value; } - } - - /// - /// The alias of the macro - are used for retrieving the macro when parsing the {?UMBRACO_MACRO}{/?UMBRACO_MACRO} element, - /// by using the alias instead of the Id, it's possible to distribute macroes from one installation to another - since the id - /// is given by an autoincrementation in the database table, and might be used by another macro in the foreing umbraco - /// - public string Alias - { - get { return MacroEntity.Alias; } - set { MacroEntity.Alias = value; } - } - - /// - /// The userfriendly name - /// - public string Name - { - get { return MacroEntity.Name; } - set { MacroEntity.Name = value; } - } - - /// - /// The relative path to the usercontrol or the assembly type of the macro when using .Net custom controls - /// - /// - /// When using a user control the value is specified like: /usercontrols/myusercontrol.ascx (with the .ascx postfix) - /// - public string Type - { - get { return MacroEntity.ControlType; } - set { MacroEntity.ControlType = value; } - } - - /// - /// The xsl file used to transform content - /// - /// Umbraco assumes that the xslfile is present in the "/xslt" folder - /// - public string Xslt - { - get { return MacroEntity.XsltPath; } - set { MacroEntity.XsltPath = value; } - } - - /// - /// This field is used to store the file value for any scripting macro such as python, ruby, razor macros or Partial View Macros - /// - /// - /// Depending on how the file is stored depends on what type of macro it is. For example if the file path is a full virtual path - /// starting with the ~/Views/MacroPartials then it is deemed to be a Partial View Macro, otherwise the file extension of the file - /// saved will determine which macro engine will be used to execute the file. - /// - public string ScriptingFile - { - get { return MacroEntity.ScriptPath; } - set { MacroEntity.ScriptPath = value; } - } - - /// - /// The python file used to be executed - /// - /// Umbraco assumes that the python file is present in the "/python" folder - /// - public bool RenderContent - { - get { return MacroEntity.DontRender == false; } - set { MacroEntity.DontRender = value == false; } - } - - /// - /// Gets or sets a value indicating whether [cache personalized]. - /// - /// true if [cache personalized]; otherwise, false. - public bool CachePersonalized - { - get { return MacroEntity.CacheByMember; } - set { MacroEntity.CacheByMember = value; } - } - - /// - /// Gets or sets a value indicating whether the macro is cached for each individual page. - /// - /// true if [cache by page]; otherwise, false. - public bool CacheByPage - { - get { return MacroEntity.CacheByPage; } - set { MacroEntity.CacheByPage = value; } - } - - /// - /// Properties which are used to send parameters to the xsl/usercontrol/customcontrol of the macro - /// - public MacroProperty[] Properties - { - get - { - return MacroEntity.Properties.Select(x => new MacroProperty - { - Key = Key, - Alias = x.Alias, - Name = x.Name, - SortOrder = x.SortOrder, - Macro = this, - ParameterEditorAlias = x.EditorAlias - }).ToArray(); - } - } - - /// - /// Macro initializer - /// - [Obsolete("This should no longer be used, use the IMacroService and related models instead")] - public Macro() - { - } - - /// - /// Macro initializer - /// - /// The id of the macro - [Obsolete("This should no longer be used, use the IMacroService and related models instead")] - public Macro(int Id) - { - Setup(Id); - } - - [Obsolete("This should no longer be used, use the IMacroService and related models instead")] - internal Macro(IMacro macro) - { - MacroEntity = macro; - } - - /// - /// Initializes a new instance of the class. - /// - /// The alias. - [Obsolete("This should no longer be used, use the IMacroService and related models instead")] - public Macro(string alias) - { - Setup(alias); - } - - /// - /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility - /// - [Obsolete("This should no longer be used, use the IMacroService and related models instead")] - public virtual void Save() - { - Current.Services.MacroService.Save(MacroEntity); - } - - /// - /// Deletes the current macro - /// - public void Delete() - { - Current.Services.MacroService.Delete(MacroEntity); - } - - [Obsolete("This is no longer used, use the IMacroService and related models instead")] - public static Macro Import(XmlNode n) - { - var alias = XmlHelper.GetNodeValue(n.SelectSingleNode("alias")); - //check to see if the macro alreay exists in the system - //it's better if it does and we keep using it, alias *should* be unique remember - - var m = Macro.GetByAlias(alias); - - - if (m == null) - { - m = MakeNew(XmlHelper.GetNodeValue(n.SelectSingleNode("name"))); - } - try - { - m.Alias = alias; - m.Type = XmlHelper.GetNodeValue(n.SelectSingleNode("scriptType")); - m.Xslt = XmlHelper.GetNodeValue(n.SelectSingleNode("xslt")); - m.RefreshRate = int.Parse(XmlHelper.GetNodeValue(n.SelectSingleNode("refreshRate"))); - - // we need to validate if the usercontrol is missing the tilde prefix requirement introduced in v6 - if (string.IsNullOrEmpty(m.Type) == false && m.Type.StartsWith("~") == false) - { - m.Type = "~/" + m.Type; - } - - if (n.SelectSingleNode("scriptingFile") != null) - { - m.ScriptingFile = XmlHelper.GetNodeValue(n.SelectSingleNode("scriptingFile")); - } - - try - { - m.UseInEditor = bool.Parse(XmlHelper.GetNodeValue(n.SelectSingleNode("useInEditor"))); - } - catch (Exception macroExp) - { - Current.Logger.Error("Error creating macro property", macroExp); - } - - // macro properties - foreach (XmlNode mp in n.SelectNodes("properties/property")) - { - try - { - var propertyAlias = mp.Attributes.GetNamedItem("alias").Value; - var property = m.Properties.SingleOrDefault(p => p.Alias == propertyAlias); - if (property != null) - { - property.Name = mp.Attributes.GetNamedItem("name").Value; - property.ParameterEditorAlias = mp.Attributes.GetNamedItem("propertyType").Value; - - property.Save(); - } - else - { - MacroProperty.MakeNew( - m, - propertyAlias, - mp.Attributes.GetNamedItem("name").Value, - mp.Attributes.GetNamedItem("propertyType").Value - ); - } - } - catch (Exception macroPropertyExp) - { - Current.Logger.Error("Error creating macro property", macroPropertyExp); - } - } - - m.Save(); - } - catch (Exception ex) - { - Current.Logger.Error("An error occurred importing a macro", ex); - return null; - } - - return m; - } - - private void Setup(int id) - { - var macro = Current.Services.MacroService.GetById(id); - - if (macro == null) - throw new ArgumentException(string.Format("No Macro exists with id '{0}'", id)); - - MacroEntity = macro; - } - - private void Setup(string alias) - { - var macro = Current.Services.MacroService.GetByAlias(alias); - - if (macro == null) - throw new ArgumentException(string.Format("No Macro exists with alias '{0}'", alias)); - - MacroEntity = macro; - } - - /// - /// Get an xmlrepresentation of the macro, used for exporting the macro to a package for distribution - /// - /// Current xmldocument context - /// An xmlrepresentation of the macro - public XmlNode ToXml(XmlDocument xd) - { - var serializer = new EntityXmlSerializer(); - var xml = serializer.Serialize(MacroEntity); - return xml.GetXmlNode(xd); - } - - [Obsolete("This does nothing")] - public void RefreshProperties() - { - } - - #region STATICS - - /// - /// Creates a new macro given the name - /// - /// Userfriendly name - /// The newly macro - public static Macro MakeNew(string Name) - { - var macro = new Umbraco.Core.Models.Macro - { - Name = Name, - Alias = Name.Replace(" ", String.Empty) - }; - - Current.Services.MacroService.Save(macro); - - var newMacro = new Macro(macro); - - return newMacro; - } - - /// - /// Retrieve all macroes - /// - /// A list of all macroes - public static Macro[] GetAll() - { - return Current.Services.MacroService.GetAll() - .Select(x => new Macro(x)) - .ToArray(); - } - - /// - /// Static contructor for retrieving a macro given an alias - /// - /// The alias of the macro - /// If the macro with the given alias exists, it returns the macro, else null - public static Macro GetByAlias(string alias) - { - return Current.ApplicationCache.RuntimeCache.GetCacheItem( - GetCacheKey(alias), - timeout: TimeSpan.FromMinutes(30), - getCacheItem: () => - { - var macro = Current.Services.MacroService.GetByAlias(alias); - if (macro == null) return null; - return new Macro(macro); - }); - } - - public static Macro GetById(int id) - { - return Current.ApplicationCache.RuntimeCache.GetCacheItem( - GetCacheKey(string.Format("macro_via_id_{0}", id)), - timeout: TimeSpan.FromMinutes(30), - getCacheItem: () => - { - var macro = Current.Services.MacroService.GetById(id); - if (macro == null) return null; - return new Macro(macro); - }); - } - - #region Macro Refactor - - private static string GetCacheKey(string alias) - { - return CacheKeys.MacroCacheKey + alias; - } - - #endregion - - #endregion - } -} diff --git a/src/umbraco.cms/businesslogic/macro/MacroProperty.cs b/src/umbraco.cms/businesslogic/macro/MacroProperty.cs deleted file mode 100644 index 07be6c3807..0000000000 --- a/src/umbraco.cms/businesslogic/macro/MacroProperty.cs +++ /dev/null @@ -1,240 +0,0 @@ -using System; -using System.Data; -using System.Xml; -using System.Runtime.CompilerServices; -using Umbraco.Core; -using Umbraco.Core.PropertyEditors; -using umbraco.DataLayer; -using umbraco.BusinessLogic; -using System.Collections.Generic; -using Umbraco.Core.Xml; - - -namespace umbraco.cms.businesslogic.macro -{ - /// - /// The macro property is used by macroes to communicate/transfer userinput to an instance of a macro. - /// - /// It contains information on which type of data is inputted aswell as the userinterface used to input data - /// - /// A MacroProperty uses it's MacroPropertyType to define which underlaying component should be used when - /// rendering the MacroProperty editor aswell as which datatype its containing. - /// - [Obsolete("This is no longer used, use the IMacroService and related models instead")] - public class MacroProperty - { - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - - /// - /// Initializes a new instance of the class. - /// - public MacroProperty() - { - Key = Guid.NewGuid(); - } - - /// - /// Constructor - /// - /// Id - public MacroProperty(int Id) - { - this.Id = Id; - Setup(); - } - - /// - /// The sortorder - /// - public int SortOrder { get; set; } - - /// - /// This is not used for anything - /// - [Obsolete("This is not used for anything and will be removed in future versions")] - public bool Public { get; set; } - - /// - /// The macro property alias - /// - public string Alias { get; set; } - - /// - /// The userfriendly name - /// - public string Name { get; set; } - - /// - /// Gets the id. - /// - /// The id. - public int Id { get; private set; } - - /// - /// Gets the key. - /// - public Guid Key { get; set; } - - /// - /// Gets or sets the macro. - /// - /// The macro. - public Macro Macro { get; set; } - - private string _parameterEditorAlias; - - /// - /// The macro parameter editor alias used to render the editor - /// - public string ParameterEditorAlias - { - get { return _parameterEditorAlias; } - set - { - //try to get the new mapped parameter editor - var mapped = LegacyParameterEditorAliasConverter.GetNewAliasFromLegacyAlias(value, false); - if (mapped.IsNullOrWhiteSpace() == false) - { - _parameterEditorAlias = mapped; - } - else - { - _parameterEditorAlias = value; - } - - } - } - - private void Setup() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader("select uniqueId, macro, editorAlias, macroPropertySortOrder, macroPropertyAlias, macroPropertyName from cmsMacroProperty where id = @id", sqlHelper.CreateParameter("@id", Id))) - { - if (dr.Read()) - { - Key = dr.GetGuid("uniqueId"); - Macro = new Macro(dr.GetInt("macro")); - SortOrder = (int)dr.GetByte("macroPropertySortOrder"); - Alias = dr.GetString("macroPropertyAlias"); - Name = dr.GetString("macroPropertyName"); - ParameterEditorAlias = dr.GetString("editorAlias"); - } - else - { - throw new ArgumentException("No macro property found for the id specified"); - } - } - } - - /// - /// Deletes the current macroproperty - /// - public void Delete() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("delete from cmsMacroProperty where id = @id", sqlHelper.CreateParameter("@id", this.Id)); - } - - public void Save() - { - if (Id == 0) - { - MacroProperty mp = MakeNew(Macro, Alias, Name, ParameterEditorAlias); - Id = mp.Id; - } - else - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("UPDATE cmsMacroProperty set macro = @macro, " + - "macropropertyAlias = @alias, macroPropertyName = @name, " + - "editorAlias = @editorAlias, macroPropertySortOrder = @so WHERE id = @id", - sqlHelper.CreateParameter("@id", Id), - sqlHelper.CreateParameter("@macro", Macro.Id), - sqlHelper.CreateParameter("@alias", Alias), - sqlHelper.CreateParameter("@name", Name), - sqlHelper.CreateParameter("@editorAlias", ParameterEditorAlias), - sqlHelper.CreateParameter("@so", SortOrder)); - } - } - - /// - /// Retrieve a Xmlrepresentation of the MacroProperty used for exporting the Macro to the package - /// - /// XmlDocument context - /// A xmlrepresentation of the object - public XmlElement ToXml(XmlDocument xd) - { - XmlElement doc = xd.CreateElement("property"); - - doc.Attributes.Append(XmlHelper.AddAttribute(xd, "name", this.Name)); - doc.Attributes.Append(XmlHelper.AddAttribute(xd, "alias", this.Alias)); - doc.Attributes.Append(XmlHelper.AddAttribute(xd, "propertyType", this.ParameterEditorAlias)); - - return doc; - } - - #region STATICS - - /// - /// Retieve all MacroProperties of a macro - /// - /// Macro identifier - /// All MacroProperties of a macro - public static MacroProperty[] GetProperties(int macroId) - { - var props = new List(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("select id from cmsMacroProperty where macro = @macroId order by macroPropertySortOrder, id ASC", sqlHelper.CreateParameter("@macroId", macroId))) - { - while (dr.Read()) - { - props.Add(new MacroProperty(dr.GetInt("id"))); - } - return props.ToArray(); - } - } - - - /// - /// Creates a new MacroProperty on a macro - /// - /// The macro - /// The alias of the property - /// Userfriendly MacroProperty name - /// The Alias of the parameter editor - [MethodImpl(MethodImplOptions.Synchronized)] - public static MacroProperty MakeNew(Macro macro, string alias, string name, string editorAlias) - { - //try to get the new mapped parameter editor - var mapped = LegacyParameterEditorAliasConverter.GetNewAliasFromLegacyAlias(editorAlias, false); - if (mapped.IsNullOrWhiteSpace() == false) - { - editorAlias = mapped; - } - - int macroPropertyId = 0; - // The method is synchronized - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - sqlHelper.ExecuteNonQuery( - "INSERT INTO cmsMacroProperty (macro, macropropertyAlias, macroPropertyName, editorAlias) VALUES (@macro, @alias, @name, @editorAlias)", - sqlHelper.CreateParameter("@macro", macro.Id), - sqlHelper.CreateParameter("@alias", alias), - sqlHelper.CreateParameter("@name", name), - sqlHelper.CreateParameter("@editorAlias", editorAlias)); - macroPropertyId = sqlHelper.ExecuteScalar("SELECT MAX(id) FROM cmsMacroProperty"); - return new MacroProperty(macroPropertyId); - } - } - - #endregion - - } -} diff --git a/src/umbraco.cms/businesslogic/media/Media.cs b/src/umbraco.cms/businesslogic/media/Media.cs deleted file mode 100644 index ff860475ed..0000000000 --- a/src/umbraco.cms/businesslogic/media/Media.cs +++ /dev/null @@ -1,347 +0,0 @@ -using System; -using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.Models; -using Umbraco.Core.Models.EntityBase; -using umbraco.BusinessLogic; -using umbraco.DataLayer; -using System.Collections; -using System.Collections.Generic; -using System.Xml; -using System.Linq; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; - -namespace umbraco.cms.businesslogic.media -{ - /// - /// A media represents a physical file and metadata on the file. - /// - /// By inheriting the Content class it has a generic datafields which enables custumization - /// - [Obsolete("Obsolete, Use Umbraco.Core.Models.Media", false)] - public class Media : Content - { - #region Constants and static members - - protected internal IMedia MediaItem; - - #endregion - - #region Constructors - - /// - /// Contructs a media object given the Id - /// - /// Identifier - public Media(int id) : base(id) { } - - /// - /// Contructs a media object given the Id - /// - /// Identifier - public Media(Guid id) : base(id) { } - - public Media(int id, bool noSetup) : base(id, noSetup) { } - - public Media(Guid id, bool noSetup) : base(id, noSetup) { } - - internal Media(IUmbracoEntity entity, bool noSetup = true) - : base(entity) - { - if (noSetup == false) - setupNode(); - } - - internal Media(IMedia media) : base(media) - { - SetupNode(media); - } - - #endregion - - #region Static Methods - /// - /// - - /// - public static Guid _objectType = new Guid(Constants.ObjectTypes.Media); - - - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.CreateMedia()", false)] - public static Media MakeNew(string Name, MediaType dct, IUser u, int ParentId) - { - var media = Current.Services.MediaService.CreateMediaWithIdentity(Name, ParentId, dct.Alias, u.Id); - //The media object will only have the 'WasCancelled' flag set to 'True' if the 'Creating' event has been cancelled - if (((Entity)media).WasCancelled) - return null; - - var tmp = new Media(media); - - return tmp; - } - - /// - /// Retrieve a list of all toplevel medias and folders - /// - /// - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetRootMedia()", false)] - public static Media[] GetRootMedias() - { - var children = Current.Services.MediaService.GetRootMedia(); - return children.Select(x => new Media(x)).ToArray(); - } - - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetChildren()", false)] - public static List GetChildrenForTree(int nodeId) - { - var children = Current.Services.MediaService.GetChildren(nodeId); - return children.Select(x => new Media(x)).ToList(); - } - - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetMediaOfMediaType()", false)] - public static IEnumerable GetMediaOfMediaType(int mediaTypeId) - { - var children = Current.Services.MediaService.GetMediaOfMediaType(mediaTypeId); - return children.Select(x => new Media(x)).ToList(); - } - - /// - /// Deletes all medias of the given type, used when deleting a mediatype - /// - /// Use with care. - /// - /// - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.DeleteMediaOfType()", false)] - public static void DeleteFromType(MediaType dt) - { - Current.Services.MediaService.DeleteMediaOfType(dt.Id); - } - - #endregion - - #region Public Properties - public override int sortOrder - { - get - { - return MediaItem == null ? base.sortOrder : MediaItem.SortOrder; - } - set - { - if (MediaItem == null) - { - base.sortOrder = value; - } - else - { - MediaItem.SortOrder = value; - } - } - } - - public override int Level - { - get - { - return MediaItem == null ? base.Level : MediaItem.Level; - } - set - { - if (MediaItem == null) - { - base.Level = value; - } - else - { - MediaItem.Level = value; - } - } - } - - public override int ParentId - { - get - { - return MediaItem == null ? base.ParentId : MediaItem.ParentId; - } - } - - public override string Path - { - get - { - return MediaItem == null ? base.Path : MediaItem.Path; - } - set - { - if (MediaItem == null) - { - base.Path = value; - } - else - { - MediaItem.Path = value; - } - } - } - - [Obsolete("Obsolete, Use Name property on Umbraco.Core.Models.Content", false)] - public override string Text - { - get - { - return MediaItem.Name; - } - set - { - value = value.Trim(); - MediaItem.Name = value; - } - } - - /// - /// Retrieve a list of all medias underneath the current - /// - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.GetChildren()", false)] - public new Media[] Children - { - get - { - //return refactored optimized method - //return Media.GetChildrenForTree(this.Id).ToArray(); - - var children = Current.Services.MediaService.GetChildren(Id).OrderBy(c => c.SortOrder); - return children.Select(x => new Media(x)).ToArray(); - } - } - - #endregion - - #region Public methods - - public override XmlNode ToXml(XmlDocument xd, bool Deep) - { - if (IsTrashed == false) - { - return base.ToXml(xd, Deep); - } - return null; - } - - - - /// - /// Moves the media to the trash - /// - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.MoveToRecycleBin()", false)] - public override void delete() - { - MoveToTrash(); - } - - /// - /// With either move the media to the trash or permanently remove it from the database. - /// - /// flag to set whether or not to completely remove it from the database or just send to trash - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.Delete() or Umbraco.Core.Services.MediaService.MoveToRecycleBin()", false)] - public void delete(bool deletePermanently) - { - if (!deletePermanently) - { - MoveToTrash(); - } - else - { - DeletePermanently(); - } - } - - #endregion - - #region Protected methods - protected override void setupNode() - { - if (Id == -1 || Id == -21) - { - base.setupNode(); - return; - } - - var media = Version == Guid.Empty - ? Current.Services.MediaService.GetById(Id) - : Current.Services.MediaService.GetByVersion(Version); - - if (media == null) - throw new ArgumentException(string.Format("No Media exists with id '{0}'", Id)); - - SetupNode(media); - } - - #endregion - - #region Private methods - private void SetupNode(IMedia media) - { - MediaItem = media; - //Also need to set the ContentBase item to this one so all the propery values load from it - ContentBase = MediaItem; - - //Setting private properties from IContentBase replacing CMSNode.setupNode() / CMSNode.PopulateCMSNodeFromReader() - base.PopulateCMSNodeFromUmbracoEntity(MediaItem, _objectType); - - //If the version is empty we update with the latest version from the current IContent. - if (Version == Guid.Empty) - Version = MediaItem.Version; - } - - /// - /// Used internally to permanently delete the data from the database - /// - /// returns true if deletion isn't cancelled - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.Delete()", false)] - private bool DeletePermanently() - { - if (MediaItem != null) - { - Current.Services.MediaService.Delete(MediaItem); - } - else - { - var media = Current.Services.MediaService.GetById(Id); - Current.Services.MediaService.Delete(media); - } - - base.delete(); - return true; - } - - /// - /// Used internally to move the node to the recyle bin - /// - /// Returns true if the move was not cancelled - [Obsolete("Obsolete, Use Umbraco.Core.Services.MediaService.MoveToRecycleBin()", false)] - private bool MoveToTrash() - { - if (MediaItem != null) - { - Current.Services.MediaService.MoveToRecycleBin(MediaItem); - } - else - { - var media = Current.Services.MediaService.GetById(Id); - Current.Services.MediaService.MoveToRecycleBin(media); - } - - //Move((int)RecycleBin.RecycleBinType.Media); - - //TODO: Now that we've moved it to trash, we need to move the actual files so they are no longer accessible - //from the original URL. - return true; - - } - - #endregion - - - } -} diff --git a/src/umbraco.cms/businesslogic/media/MediaFactory.cs b/src/umbraco.cms/businesslogic/media/MediaFactory.cs deleted file mode 100644 index ebab9dfb19..0000000000 --- a/src/umbraco.cms/businesslogic/media/MediaFactory.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.IO; - -namespace umbraco.cms.businesslogic.media -{ - - public class PostedMediaFile - { - public string FileName { get; set; } - public string DisplayName { get; set; } - public string ContentType { get; set; } - public int ContentLength { get; set; } - public Stream InputStream { get; set; } - public bool ReplaceExisting { get; set; } - - public void SaveAs(string filename) - { - using (var s = new FileStream(filename, FileMode.Create)) - { - try - { - int readCount; - var buffer = new byte[8192]; - - if (InputStream.CanSeek) - InputStream.Seek(0, SeekOrigin.Begin); - - while ((readCount = InputStream.Read(buffer, 0, buffer.Length)) != 0) - s.Write(buffer, 0, readCount); - - s.Flush(); - } - finally - { - s.Close(); - } - } - - } - } -} diff --git a/src/umbraco.cms/businesslogic/media/MediaType.cs b/src/umbraco.cms/businesslogic/media/MediaType.cs deleted file mode 100644 index 9f820f2389..0000000000 --- a/src/umbraco.cms/businesslogic/media/MediaType.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using Umbraco.Core; -using Umbraco.Core.Models; -using System.Linq; -using System.Threading; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Security; - -namespace umbraco.cms.businesslogic.media -{ - /// - /// The Mediatype - /// - /// Due to the inheritance of the ContentType class,it enables definition of generic datafields on a Media. - /// - [Obsolete("Obsolete, Use Umbraco.Core.Models.MediaType", false)] - public class MediaType : ContentType - { - #region Constructors - - /// - /// Constructs a MediaTypeobject given the id - /// - /// Id of the mediatype - public MediaType(int id) : base(id) { } - - /// - /// Constructs a MediaTypeobject given the id - /// - /// Id of the mediatype - public MediaType(Guid id) : base(id) { } - - public MediaType(int id, bool noSetup) : base(id, noSetup) { } - - internal MediaType(IMediaType mediaType) - : base(mediaType) - { - SetupNode(mediaType); - } - - #endregion - - #region Constants and static members - - public static Guid _objectType = new Guid(Constants.ObjectTypes.MediaType); - - #endregion - - #region Private Members - - private IMediaType MediaTypeItem - { - get { return base.ContentTypeItem as IMediaType; } - set { base.ContentTypeItem = value; } - } - - #endregion - - #region Static Methods - /// - /// Retrieve a MediaType by it's alias - /// - /// The alias of the MediaType - /// The MediaType with the alias - [Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.GetMediaType()", false)] - public static new MediaType GetByAlias(string Alias) - { - var mediaType = Current.Services.MediaTypeService.Get(Alias); - return new MediaType(mediaType); - } - - /// - /// Retrieve all MediaTypes in the umbraco installation - /// - [Obsolete("Use the GetAllAsList() method instead")] - public new static MediaType[] GetAll - { - get - { - return GetAllAsList().ToArray(); - } - } - - [Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.GetMediaType()", false)] - public static IEnumerable GetAllAsList() - { - var mediaTypes = Current.Services.MediaTypeService.GetAll(); - return mediaTypes.OrderBy(x => x.Name).Select(x => new MediaType(x)); - } - - [Obsolete("Obsolete, Use Umbraco.Core.Models.MediaType and Umbraco.Core.Services.ContentTypeService.Save()", false)] - public static MediaType MakeNew(IUser u, string Text) - { - return MakeNew(u, Text, -1); - } - - internal static MediaType MakeNew(IUser u, string text, int parentId) - { - var mediaType = new Umbraco.Core.Models.MediaType(parentId) { Name = text, Alias = text, CreatorId = u.Id, Thumbnail = "icon-folder", Icon = "icon-folder" }; - Current.Services.MediaTypeService.Save(mediaType, u.Id); - var mt = new MediaType(mediaType.Id); - - - return mt; - } - #endregion - - #region Public Methods - /// - /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility - /// - public override void Save() - { - var current = Thread.CurrentPrincipal != null ? Thread.CurrentPrincipal.Identity as UmbracoBackOfficeIdentity : null; - var userId = current == null ? Attempt.Fail() : current.Id.TryConvertTo(); - Current.Services.MediaTypeService.Save(MediaTypeItem, userId.Success ? userId.Result : 0); - - base.Save(); - - - } - - /// - /// Deletes the current MediaType and all created Medias of the type. - /// - public override void delete() - { - // check that no media types uses me as a master - if (GetAllAsList().Any(dt => dt.MasterContentTypes.Contains(this.Id))) - { - throw new ArgumentException("Can't delete a Media Type used as a Master Content Type. Please remove all references first!"); - } - - Current.Services.MediaTypeService.Delete(MediaTypeItem); - - - } - #endregion - - #region Protected Methods - - protected override void setupNode() - { - var mediaType = Current.Services.MediaTypeService.Get(Id); - // If it's null, it's probably a folder - if (mediaType != null) - SetupNode(mediaType); - } - - #endregion - - #region Private Methods - private void SetupNode(IMediaType mediaType) - { - MediaTypeItem = mediaType; - - base.PopulateContentTypeFromContentTypeBase(MediaTypeItem); - base.PopulateCMSNodeFromUmbracoEntity(MediaTypeItem, _objectType); - } - #endregion - - - } -} diff --git a/src/umbraco.cms/businesslogic/member/Member.cs b/src/umbraco.cms/businesslogic/member/Member.cs deleted file mode 100644 index 6fdb93b267..0000000000 --- a/src/umbraco.cms/businesslogic/member/Member.cs +++ /dev/null @@ -1,1101 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Web; -using System.Xml; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Models.EntityBase; -using Umbraco.Core.Persistence.Querying; -using umbraco.DataLayer; -using System.Web.Security; -using System.Text; -using System.Security.Cryptography; -using System.Linq; -using Umbraco.Core.Composing; -using Umbraco.Core.Exceptions; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Security; -using Umbraco.Core.Xml; - -namespace umbraco.cms.businesslogic.member -{ - /// - /// The Member class represents a member of the public website (not to be confused with umbraco users) - /// - /// Members are used when creating communities and collaborative applications using umbraco, or if there are a - /// need for identifying or authentifying the visitor. (extranets, protected/private areas of the public website) - /// - /// Inherits generic datafields from it's baseclass content. - /// - [Obsolete("Use the MemberService and the Umbraco.Core.Models.Member models instead")] - public class Member : Content - { - #region Constants and static members - public static readonly string UmbracoMemberProviderName = Constants.Conventions.Member.UmbracoMemberProviderName; - public static readonly string UmbracoRoleProviderName = Constants.Conventions.Member.UmbracoRoleProviderName; - public static readonly Guid _objectType = new Guid(Constants.ObjectTypes.Member); - - // zb-00004 #29956 : refactor cookies names & handling - - private const string _sQLOptimizedMany = @" - select - umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level, - umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate, - umbracoNode.nodeUser, umbracoNode.text, - cmsMember.Email, cmsMember.LoginName, cmsMember.Password - from umbracoNode - inner join cmsContent on cmsContent.nodeId = umbracoNode.id - inner join cmsMember on cmsMember.nodeId = cmsContent.nodeId - where umbracoNode.nodeObjectType = @nodeObjectType AND {0} - order by {1}"; - - #endregion - - #region Private members - - private Dictionary _groups = null; - protected internal IMember MemberItem; - - #endregion - - #region Constructors - - internal Member(IMember member) - : base(member) - { - SetupNode(member); - } - - /// - /// Initializes a new instance of the Member class. - /// - /// Identifier - public Member(int id) : base(id) { } - - /// - /// Initializes a new instance of the Member class. - /// - /// Identifier - public Member(Guid id) : base(id) { } - - /// - /// Initializes a new instance of the Member class, with an option to only initialize - /// the data used by the tree in the umbraco console. - /// - /// Identifier - /// - public Member(int id, bool noSetup) : base(id, noSetup) { } - - public Member(Guid id, bool noSetup) : base(id, noSetup) { } - - #endregion - - #region Static methods - /// - /// A list of all members in the current umbraco install - /// - /// Note: is ressource intensive, use with care. - /// - public static Member[] GetAll - { - get - { - return GetAllAsList().ToArray(); - } - } - - public static IEnumerable GetAllAsList() - { - long totalRecs; - return Current.Services.MemberService.GetAll(0, int.MaxValue, out totalRecs) - .Select(x => new Member(x)) - .ToArray(); - } - - /// - /// Retrieves a list of members thats not start with a-z - /// - /// array of members - public static Member[] getAllOtherMembers() - { - - //NOTE: This hasn't been ported to the new service layer because it is an edge case, it is only used to render the tree nodes but in v7 we plan on - // changing how the members are shown and not having to worry about letters. - - var ids = new List(); - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader( - string.Format(_sQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')", "umbracoNode.text"), - sqlHelper.CreateParameter("@nodeObjectType", Member._objectType))) - { - - while (dr.Read()) - { - ids.Add(dr.GetInt("id")); - } - } - - if (ids.Any()) - { - return Current.Services.MemberService.GetAllMembers(ids.ToArray()) - .Select(x => new Member(x)) - .ToArray(); - } - - return new Member[] { }; - } - - /// - /// Retrieves a list of members by the first letter in their name. - /// - /// The first letter - /// - public static Member[] getMemberFromFirstLetter(char letter) - { - long totalRecs; - - return Current.Services.MemberService.FindMembersByDisplayName( - letter.ToString(CultureInfo.InvariantCulture), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith) - .Select(x => new Member(x)) - .ToArray(); - } - - public static Member[] GetMemberByName(string usernameToMatch, bool matchByNameInsteadOfLogin) - { - long totalRecs; - if (matchByNameInsteadOfLogin) - { - var found = Current.Services.MemberService.FindMembersByDisplayName( - usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); - return found.Select(x => new Member(x)).ToArray(); - } - else - { - var found = Current.Services.MemberService.FindByUsername( - usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); - return found.Select(x => new Member(x)).ToArray(); - } - } - - /// - /// Creates a new member - /// - /// Membername - /// Member type - /// The umbraco usercontext - /// The new member - public static Member MakeNew(string Name, MemberType mbt, IUser u) - { - return MakeNew(Name, "", "", mbt, u); - } - - - /// - /// Creates a new member - /// - /// Membername - /// Member type - /// The umbraco usercontext - /// The email of the user - /// The new member - public static Member MakeNew(string Name, string Email, MemberType mbt, IUser u) - { - return MakeNew(Name, "", Email, mbt, u); - } - - /// - /// Creates a new member - /// - /// Membername - /// Member type - /// The umbraco usercontext - /// The email of the user - /// The new member - public static Member MakeNew(string Name, string LoginName, string Email, MemberType mbt, IUser u) - { - if (mbt == null) throw new ArgumentNullException("mbt"); - var loginName = (string.IsNullOrEmpty(LoginName) == false) ? LoginName : Name; - - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - - //NOTE: This check is ONLY for backwards compatibility, this check shouldn't really be here it is up to the Membership provider - // logic to deal with this but it was here before so we can't really change that. - // Test for e-mail - if (Email != "" && GetMemberFromEmail(Email) != null && provider.RequiresUniqueEmail) - throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email)); - if (GetMemberFromLoginName(loginName) != null) - throw new Exception(string.Format("Duplicate User name! A member with the user name {0} already exists", loginName)); - - var model = Current.Services.MemberService.CreateMemberWithIdentity( - loginName, Email.ToLower(), Name, mbt.MemberTypeItem); - - //The content object will only have the 'WasCancelled' flag set to 'True' if the 'Saving' event has been cancelled, so we return null. - if (((Entity)model).WasCancelled) - return null; - - var legacy = new Member(model); - - - legacy.Save(); - - return legacy; - } - - /// - /// Retrieve a member given the loginname - /// - /// Used when authentifying the Member - /// - /// The unique Loginname - /// The member with the specified loginname - null if no Member with the login exists - public static Member GetMemberFromLoginName(string loginName) - { - if (string.IsNullOrEmpty(loginName)) throw new ArgumentNullOrEmptyException(nameof(loginName)); - - var found = Current.Services.MemberService.GetByUsername(loginName); - if (found == null) return null; - - return new Member(found); - } - - /// - /// Retrieve a Member given an email, the first if there multiple members with same email - /// - /// Used when authentifying the Member - /// - /// The email of the member - /// The member with the specified email - null if no Member with the email exists - public static Member GetMemberFromEmail(string email) - { - if (string.IsNullOrEmpty(email)) - return null; - - var found = Current.Services.MemberService.GetByEmail(email); - if (found == null) return null; - - return new Member(found); - } - - /// - /// Retrieve Members given an email - /// - /// Used when authentifying a Member - /// - /// The email of the member(s) - /// The members with the specified email - public static Member[] GetMembersFromEmail(string email) - { - if (string.IsNullOrEmpty(email)) - return null; - - long totalRecs; - var found = Current.Services.MemberService.FindByEmail( - email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact); - - return found.Select(x => new Member(x)).ToArray(); - } - - /// - /// Retrieve a Member given the credentials - /// - /// Used when authentifying the member - /// - /// Member login - /// Member password - /// The member with the credentials - null if none exists - [Obsolete("Use the MembershipProvider methods to validate a member")] - public static Member GetMemberFromLoginNameAndPassword(string loginName, string password) - { - if (IsMember(loginName)) - { - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - - // validate user via provider - if (provider.ValidateUser(loginName, password)) - { - return GetMemberFromLoginName(loginName); - } - else - { - Current.Logger.Debug("Incorrect login/password attempt or member is locked out or not approved (" + loginName + ")"); - return null; - } - } - else - { - Current.Logger.Debug("No member with loginname: " + loginName + " Exists"); - return null; - } - } - - [Obsolete("This method will not work if the password format is encrypted since the encryption that is performed is not static and a new value will be created each time the same string is encrypted")] - public static Member GetMemberFromLoginAndEncodedPassword(string loginName, string password) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - var o = sqlHelper.ExecuteScalar( - "select nodeID from cmsMember where LoginName = @loginName and Password = @password", - sqlHelper.CreateParameter("loginName", loginName), - sqlHelper.CreateParameter("password", password)); - - if (o == null) - return null; - - int tmpId; - if (!int.TryParse(o.ToString(), out tmpId)) - return null; - - return new Member(tmpId); - } - } - - [Obsolete("Use MembershipProviderExtensions.IsUmbracoMembershipProvider instead")] - public static bool InUmbracoMemberMode() - { - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - return provider.IsUmbracoMembershipProvider(); - } - - public static bool IsUsingUmbracoRoles() - { - return Roles.Provider.Name == UmbracoRoleProviderName; - } - - - /// - /// Helper method - checks if a Member with the LoginName exists - /// - /// Member login - /// True if the member exists - public static bool IsMember(string loginName) - { - if (string.IsNullOrWhiteSpace(loginName)) throw new ArgumentNullOrEmptyException(nameof(loginName)); - return Current.Services.MemberService.Exists(loginName); - } - - /// - /// Deletes all members of the membertype specified - /// - /// Used when a membertype is deleted - /// - /// Use with care - /// - /// The membertype which are being deleted - public static void DeleteFromType(MemberType dt) - { - Current.Services.MemberService.DeleteMembersOfType(dt.Id); - } - - #endregion - - #region Public Properties - - public override int sortOrder - { - get - { - return MemberItem == null ? base.sortOrder : MemberItem.SortOrder; - } - set - { - if (MemberItem == null) - { - base.sortOrder = value; - } - else - { - MemberItem.SortOrder = value; - } - } - } - - public override int Level - { - get - { - return MemberItem == null ? base.Level : MemberItem.Level; - } - set - { - if (MemberItem == null) - { - base.Level = value; - } - else - { - MemberItem.Level = value; - } - } - } - - public override int ParentId - { - get - { - return MemberItem == null ? base.ParentId : MemberItem.ParentId; - } - } - - public override string Path - { - get - { - return MemberItem == null ? base.Path : MemberItem.Path; - } - set - { - if (MemberItem == null) - { - base.Path = value; - } - else - { - MemberItem.Path = value; - } - } - } - - [Obsolete("Obsolete, Use Name property on Umbraco.Core.Models.Content", false)] - public override string Text - { - get - { - return MemberItem.Name; - } - set - { - value = value.Trim(); - MemberItem.Name = value; - } - } - - /// - /// The members password, used when logging in on the public website - /// - [Obsolete("Do not use this property, use GetPassword and ChangePassword instead, if using ChangePassword ensure that the password is encrypted or hashed based on the active membership provider")] - public string Password - { - get - { - return MemberItem.RawPasswordValue; - } - set - { - // We need to use the provider for this in order for hashing, etc. support - // To write directly to the db use the ChangePassword method - // this is not pretty but nessecary due to a design flaw (the membership provider should have been a part of the cms project) - var helper = new MemberShipHelper(); - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - MemberItem.RawPasswordValue = helper.EncodePassword(value, provider.PasswordFormat); - } - } - - /// - /// The loginname of the member, used when logging in - /// - public string LoginName - { - get - { - return MemberItem.Username; - } - set - { - if (string.IsNullOrEmpty(value)) - throw new ArgumentException("The loginname must be different from an empty string", "LoginName"); - if (value.Contains(",")) - throw new ArgumentException("The parameter 'LoginName' must not contain commas."); - MemberItem.Username = value; - } - } - - /// - /// A list of groups the member are member of - /// - public Dictionary Groups - { - get - { - if (_groups == null) - PopulateGroups(); - return _groups; - } - } - - /// - /// The members email - /// - public string Email - { - get - { - return MemberItem.Email.IsNullOrWhiteSpace() ? string.Empty : MemberItem.Email.ToLower(); - } - set - { - MemberItem.Email = value == null ? "" : value.ToLower(); - } - } - #endregion - - #region Public Methods - - [Obsolete("Obsolete", false)] - protected override void setupNode() - { - if (Id == -1) - { - base.setupNode(); - return; - } - - var content = Current.Services.MemberService.GetById(Id); - - if (content == null) - throw new ArgumentException(string.Format("No Member exists with id '{0}'", Id)); - - SetupNode(content); - } - - private void SetupNode(IMember content) - { - MemberItem = content; - //Also need to set the ContentBase item to this one so all the propery values load from it - ContentBase = MemberItem; - - //Setting private properties from IContentBase replacing CMSNode.setupNode() / CMSNode.PopulateCMSNodeFromReader() - base.PopulateCMSNodeFromUmbracoEntity(MemberItem, _objectType); - - //If the version is empty we update with the latest version from the current IContent. - if (Version == Guid.Empty) - Version = MemberItem.Version; - } - - - /// - /// Xmlrepresentation of a member - /// - /// The xmldocument context - /// Recursive - should always be set to false - /// A the xmlrepresentation of the current member - public override XmlNode ToXml(XmlDocument xd, bool Deep) - { - var x = base.ToXml(xd, Deep); - if (x.Attributes != null && x.Attributes["loginName"] == null) - { - x.Attributes.Append(XmlHelper.AddAttribute(xd, "loginName", LoginName)); - } - if (x.Attributes != null && x.Attributes["email"] == null) - { - x.Attributes.Append(XmlHelper.AddAttribute(xd, "email", Email)); - } - if (x.Attributes != null && x.Attributes["key"] == null) - { - x.Attributes.Append(XmlHelper.AddAttribute(xd, "key", UniqueId.ToString())); - } - return x; - } - - /// - /// Deltes the current member - /// - [Obsolete("Obsolete, Use Umbraco.Core.Services.MemberService.Delete()", false)] - public override void delete() - { - if (MemberItem != null) - { - Current.Services.MemberService.Delete(MemberItem); - } - else - { - var member = Current.Services.MemberService.GetById(Id); - Current.Services.MemberService.Delete(member); - } - - // Delete all content and cmsnode specific data! - base.delete(); - - } - - /// - /// Sets the password for the user - ensure it is encrypted or hashed based on the active membership provider - you must - /// call Save() after using this method - /// - /// - public void ChangePassword(string newPassword) - { - MemberItem.RawPasswordValue = newPassword; - } - - /// - /// Returns the currently stored password - this may be encrypted or hashed string depending on the active membership provider - /// - /// - public string GetPassword() - { - return MemberItem.RawPasswordValue; - } - - /// - /// Adds the member to group with the specified id - /// - /// The id of the group which the member is being added to - [MethodImpl(MethodImplOptions.Synchronized)] - public void AddGroup(int GroupId) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - { - var parameters = new IParameter[] { sqlHelper.CreateParameter("@id", Id), - sqlHelper.CreateParameter("@groupId", GroupId) }; - bool exists = sqlHelper.ExecuteScalar("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId", - parameters) > 0; - if (!exists) - sqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)", - parameters); - } - - PopulateGroups(); - - } - - /// - /// Removes the member from the MemberGroup specified - /// - /// The MemberGroup from which the Member is removed - public void RemoveGroup(int GroupId) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId", - sqlHelper.CreateParameter("@id", Id), sqlHelper.CreateParameter("@groupId", GroupId)); - PopulateGroups(); - } - #endregion - - #region Private methods - - private void PopulateGroups() - { - var temp = new Dictionary(); - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader( - "select memberGroup from cmsMember2MemberGroup where member = @id", - sqlHelper.CreateParameter("@id", Id))) - { - while (dr.Read()) - { - var group = Current.Services.MemberGroupService.GetById(dr.GetInt("memberGroup")); - if (group != null) - { - temp.Add(dr.GetInt("memberGroup"), group); - } - } - - } - _groups = temp; - } - - private static string GetCacheKey(int id) - { - return string.Format("{0}{1}", CacheKeys.MemberBusinessLogicCacheKey, id); - } - - #endregion - - #region MemberHandle functions - - /// - /// Method is used when logging a member in. - /// - /// Adds the member to the cache of logged in members - /// - /// Uses cookiebased recognition - /// - /// Can be used in the runtime - /// - /// The member to log in - [Obsolete("Use Membership APIs and FormsAuthentication to handle member login")] - public static void AddMemberToCache(Member m) - { - - if (m != null) - { - // Add cookie with member-id, guid and loginname - // zb-00035 #29931 : cleanup member state management - // NH 4.7.1: We'll no longer use legacy cookies to handle Umbraco Members - //SetMemberState(m); - - FormsAuthentication.SetAuthCookie(m.LoginName, true); - - //cache the member - var cachedMember = Current.ApplicationCache.RuntimeCache.GetCacheItem( - GetCacheKey(m.Id), - timeout: TimeSpan.FromMinutes(30), - getCacheItem: () => - { - // Debug information - HttpContext.Current.Trace.Write("member", - string.Format("Member added to cache: {0}/{1} ({2})", - m.Text, m.LoginName, m.Id)); - - return m; - }); - } - - } - - // zb-00035 #29931 : remove old cookie code - /// - /// Method is used when logging a member in. - /// - /// Adds the member to the cache of logged in members - /// - /// Uses cookie or session based recognition - /// - /// Can be used in the runtime - /// - /// The member to log in - /// create a persistent cookie - /// Has no effect - [Obsolete("Use the membership api and FormsAuthentication to log users in, this method is no longer used anymore")] - public static void AddMemberToCache(Member m, bool UseSession, TimeSpan TimespanForCookie) - { - if (m != null) - { - // zb-00035 #29931 : cleanup member state management - // NH 4.7.1: We'll no longer use Umbraco legacy cookies to handle members - //SetMemberState(m, UseSession, TimespanForCookie.TotalDays); - - FormsAuthentication.SetAuthCookie(m.LoginName, !UseSession); - - //cache the member - var cachedMember = Current.ApplicationCache.RuntimeCache.GetCacheItem( - GetCacheKey(m.Id), - timeout: TimeSpan.FromMinutes(30), - getCacheItem: () => - { - // Debug information - HttpContext.Current.Trace.Write("member", - string.Format("Member added to cache: {0}/{1} ({2})", - m.Text, m.LoginName, m.Id)); - - return m; - }); - - } - } - - /// - /// Removes the member from the cache - /// - /// Can be used in the public website - /// - /// Member to remove - [Obsolete("Obsolete, use the RemoveMemberFromCache(int NodeId) instead", false)] - public static void RemoveMemberFromCache(Member m) - { - RemoveMemberFromCache(m.Id); - } - - /// - /// Removes the member from the cache - /// - /// Can be used in the public website - /// - /// Node Id of the member to remove - [Obsolete("Member cache is automatically cleared when members are updated")] - public static void RemoveMemberFromCache(int NodeId) - { - Current.ApplicationCache.RuntimeCache.ClearCacheItem(GetCacheKey(NodeId)); - } - - /// - /// Retrieve a collection of members in the cache - /// - /// Can be used from the public website - /// - /// A collection of cached members - public static Hashtable CachedMembers() - { - var h = new Hashtable(); - - var items = Current.ApplicationCache.RuntimeCache.GetCacheItemsByKeySearch( - CacheKeys.MemberBusinessLogicCacheKey); - foreach (var i in items) - { - h.Add(i.Id, i); - } - return h; - } - - /// - /// Retrieve a member from the cache - /// - /// Can be used from the public website - /// - /// Id of the member - /// If the member is cached it returns the member - else null - public static Member GetMemberFromCache(int id) - { - Hashtable members = CachedMembers(); - if (members.ContainsKey(id)) - return (Member)members[id]; - else - return null; - } - - /// - /// An indication if the current visitor is logged in - /// - /// Can be used from the public website - /// - /// True if the the current visitor is logged in - [Obsolete("Use the standard ASP.Net procedures for hanlding FormsAuthentication, simply check the HttpContext.User and HttpContext.User.Identity.IsAuthenticated to determine if a member is logged in or not")] - public static bool IsLoggedOn() - { - return HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated; - } - - /// - /// Gets the current visitors memberid - /// - /// The current visitors members id, if the visitor is not logged in it returns 0 - public static int CurrentMemberId() - { - int currentMemberId = 0; - - // For backwards compatibility between umbraco members and .net membership - if (HttpContext.Current.User.Identity.IsAuthenticated) - { - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - var member = provider.GetCurrentUser(); - if (member == null) - { - throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName()); - } - int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId); - } - - return currentMemberId; - } - - /// - /// Get the current member - /// - /// Returns the member, if visitor is not logged in: null - public static Member GetCurrentMember() - { - try - { - if (HttpContext.Current.User.Identity.IsAuthenticated) - { - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - var member = provider.GetCurrentUser(); - if (member == null) - { - throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName()); - } - - int currentMemberId = 0; - if (int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId)) - { - var m = new Member(currentMemberId); - return m; - } - } - } - catch (Exception ex) - { - Current.Logger.Error("An error occurred in GetCurrentMember", ex); - } - return null; - } - - #endregion - - #region Membership helper class used for encryption methods - /// - /// ONLY FOR INTERNAL USE. - /// This is needed due to a design flaw where the Umbraco membership provider is located - /// in a separate project referencing this project, which means we can't call special methods - /// directly on the UmbracoMemberShipMember class. - /// This is a helper implementation only to be able to use the encryption functionality - /// of the membership provides (which are protected). - /// - /// ... which means this class should have been marked internal with a Friend reference to the other assembly right?? - /// - internal class MemberShipHelper : MembershipProvider - { - public override string ApplicationName - { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } - } - - public override bool ChangePassword(string username, string oldPassword, string newPassword) - { - throw new NotImplementedException(); - } - - public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) - { - throw new NotImplementedException(); - } - - public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) - { - throw new NotImplementedException(); - } - - public override bool DeleteUser(string username, bool deleteAllRelatedData) - { - throw new NotImplementedException(); - } - - public string EncodePassword(string password, MembershipPasswordFormat pwFormat) - { - string encodedPassword = password; - switch (pwFormat) - { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - encodedPassword = - Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); - break; - case MembershipPasswordFormat.Hashed: - HMACSHA1 hash = new HMACSHA1(); - hash.Key = Encoding.Unicode.GetBytes(password); - encodedPassword = - Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); - break; - } - return encodedPassword; - } - - public override bool EnablePasswordReset - { - get { throw new NotImplementedException(); } - } - - public override bool EnablePasswordRetrieval - { - get { throw new NotImplementedException(); } - } - - public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } - - public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } - - public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } - - public override int GetNumberOfUsersOnline() - { - throw new NotImplementedException(); - } - - public override string GetPassword(string username, string answer) - { - throw new NotImplementedException(); - } - - public override MembershipUser GetUser(string username, bool userIsOnline) - { - throw new NotImplementedException(); - } - - public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) - { - throw new NotImplementedException(); - } - - public override string GetUserNameByEmail(string email) - { - throw new NotImplementedException(); - } - - public override int MaxInvalidPasswordAttempts - { - get { throw new NotImplementedException(); } - } - - public override int MinRequiredNonAlphanumericCharacters - { - get { throw new NotImplementedException(); } - } - - public override int MinRequiredPasswordLength - { - get { throw new NotImplementedException(); } - } - - public override int PasswordAttemptWindow - { - get { throw new NotImplementedException(); } - } - - public override MembershipPasswordFormat PasswordFormat - { - get { throw new NotImplementedException(); } - } - - public override string PasswordStrengthRegularExpression - { - get { throw new NotImplementedException(); } - } - - public override bool RequiresQuestionAndAnswer - { - get { throw new NotImplementedException(); } - } - - public override bool RequiresUniqueEmail - { - get { throw new NotImplementedException(); } - } - - public override string ResetPassword(string username, string answer) - { - throw new NotImplementedException(); - } - - public override bool UnlockUser(string userName) - { - throw new NotImplementedException(); - } - - public override void UpdateUser(MembershipUser user) - { - throw new NotImplementedException(); - } - - public override bool ValidateUser(string username, string password) - { - throw new NotImplementedException(); - } - } - #endregion - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/member/MemberType.cs b/src/umbraco.cms/businesslogic/member/MemberType.cs deleted file mode 100644 index f08f11456d..0000000000 --- a/src/umbraco.cms/businesslogic/member/MemberType.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System; -using System.Linq; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Events; -using Umbraco.Core.Models; -using Umbraco.Core.Models.Membership; -using PropertyType = umbraco.cms.businesslogic.propertytype.PropertyType; - -namespace umbraco.cms.businesslogic.member -{ - /// MemberType - /// - /// Due to the inheritance of the ContentType class, it enables definition of generic datafields on a Members. - [Obsolete("Obsolete, Use the MemberTypeService and Umbraco.Core.Models.MemberType", false)] - public class MemberType : ContentType - { - #region Private Members - - internal static readonly Guid ObjectType = new Guid(Constants.ObjectTypes.MemberType); - internal IMemberType MemberTypeItem - { - get { return base.ContentTypeItem as IMemberType; } - set { base.ContentTypeItem = value; } - } - - #endregion - - #region Constructors - - internal MemberType(IMemberType memberType) - : base(memberType) - { - SetupNode(memberType); - } - - /// - /// Initializes a new instance of the MemberType class. - /// - /// MemberType id - public MemberType(int id) : base(id) { } - - /// - /// Initializes a new instance of the MemberType class. - /// - /// MemberType id - public MemberType(Guid id) : base(id) { } - - #region Regenerate Xml Structures - - - #endregion - - #endregion - - #region Public Methods - - /// - /// Get an true/false if the Member can edit the given data defined in the propertytype - /// - /// Propertytype to edit - /// True if the Member can edit the data - public bool MemberCanEdit(PropertyType pt) - { - return MemberTypeItem.MemberCanEditProperty(pt.Alias); - } - - /// - /// Get an true/false if the given data defined in the propertytype, should be visible on the members profile page - /// - /// Propertytype - /// True if the data should be displayed on the profilepage - public bool ViewOnProfile(PropertyType pt) - { - return MemberTypeItem.MemberCanViewProperty(pt.Alias); - } - - /// - /// Set if the member should be able to edit the data defined by its propertytype - /// - /// PropertyType - /// True/False if Members of the type shoúld be able to edit the data - public void setMemberCanEdit(PropertyType pt, bool value) - { - MemberTypeItem.SetMemberCanEditProperty(pt.Alias, value); - } - - /// - /// Set if the data should be displayed on members of this type's profilepage - /// - /// PropertyType - /// True/False if the data should be displayed - public void setMemberViewOnProfile(PropertyType pt, bool value) - { - MemberTypeItem.SetMemberCanViewProperty(pt.Alias, value); - } - - /// - /// Delete the current MemberType. - /// - /// Deletes all Members of the type - /// - /// Use with care - /// - public override void delete() - { - Current.Services.MemberTypeService.Delete(MemberTypeItem); - - } - - /// - /// Used to persist object changes to the database - /// - public override void Save() - { - Current.Services.MemberTypeService.Save(MemberTypeItem); - base.Save(); - } - - - #endregion - - #region Public Static Methods - /// - /// Get a MemberType by it's alias - /// - /// The alias of the MemberType - /// The MemberType with the given Alias - public new static MemberType GetByAlias(string Alias) - { - var result = Current.Services.MemberTypeService.Get(Alias); - return result == null ? null : new MemberType(result); - } - - /// - /// Create a new MemberType - /// - /// The name of the MemberType - /// Creator of the MemberType - public static MemberType MakeNew(IUser u, string Text) - { - var alias = Text.ToSafeAliasWithForcingCheck(); - //special case, if it stars with an underscore, we have to re-add it for member types - if (Text.StartsWith("_")) alias = "_" + alias; - var mt = new Umbraco.Core.Models.MemberType(-1) - { - Level = 1, - Name = Text, - Icon = "icon-user", - Alias = alias - }; - Current.Services.MemberTypeService.Save(mt); - var legacy = new MemberType(mt); - return legacy; - } - - /// - /// Retrieve a list of all MemberTypes - /// - public new static MemberType[] GetAll - { - get - { - var result = Current.Services.MemberTypeService.GetAll(); - return result.Select(x => new MemberType(x)).ToArray(); - } - } - #endregion - - #region Protected Methods - - protected override void setupNode() - { - var memberType = Current.Services.MemberTypeService.Get(Id); - SetupNode(memberType); - } - - #endregion - - #region Private Methods - - private void SetupNode(IMemberType contentType) - { - MemberTypeItem = contentType; - - base.PopulateContentTypeFromContentTypeBase(MemberTypeItem); - base.PopulateCMSNodeFromUmbracoEntity(MemberTypeItem, ObjectType); - } - - #endregion - - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/propertytype/PropertyTypeGroup.cs b/src/umbraco.cms/businesslogic/propertytype/PropertyTypeGroup.cs deleted file mode 100644 index 1d224237cf..0000000000 --- a/src/umbraco.cms/businesslogic/propertytype/PropertyTypeGroup.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using umbraco.BusinessLogic; -using umbraco.DataLayer; - -namespace umbraco.cms.businesslogic.propertytype -{ - public class PropertyTypeGroup - { - public int Id { get; set; } - public int ContentTypeId { get; set; } - public string Name { get; set; } - public int SortOrder { get; set; } - - public PropertyTypeGroup() - { - } - - public PropertyTypeGroup(int contentTypeId, string name, int sortOrder) - { - ContentTypeId = contentTypeId; - Name = name; - SortOrder = sortOrder; - } - - public PropertyTypeGroup(int contentTypeId, string name) - { - ContentTypeId = contentTypeId; - Name = name; - SortOrder = -1; // we set this to -1 so in the save method we can get the current highest sortorder in case it's not sat after init (ie. if you want to force a sortOrder) - } - - public IEnumerable GetPropertyTypes(List contentTypeIds) - { - return PropertyType.GetPropertyTypesByGroup(Id, contentTypeIds); - } - - public IEnumerable GetPropertyTypes() - { - return PropertyType.GetPropertyTypesByGroup(Id); - } - - // note: this is used to delete all groups that inherit from a group, when the group is deleted, - // see the Delete method in this class - but it is all done in an obsolete way which does not - // take compositions in account + we delete the group but do not re-allocate the properties, etc. - // ALL THIS should be either removed, or refactored to use the new APIs - so... returning nothing - // from now on, which is just another way of being broken. - public IEnumerable GetPropertyTypeGroups() - { - return Enumerable.Empty(); - } - - public void Save() - { - if (Id != 0) - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - @"UPDATE - cmsPropertyTypeGroup - SET - contenttypeNodeId = @contentTypeId, - sortOrder = @sortOrder, - text = @name - WHERE - id = @id - ", - sqlHelper.CreateParameter("@id", Id), - sqlHelper.CreateParameter("@contentTypeId", ContentTypeId), - sqlHelper.CreateParameter("@sortOrder", SortOrder), - sqlHelper.CreateParameter("@name", Name) - ); - } - else - { - if (SortOrder == -1) - using (var sqlHelper = LegacySqlHelper.SqlHelper) - SortOrder = sqlHelper.ExecuteScalar("select count(*) from cmsPropertyTypeGroup where contenttypeNodeId = @nodeId", - sqlHelper.CreateParameter("@nodeId", ContentTypeId)) + 1; - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - @" - INSERT INTO - cmsPropertyTypeGroup - (contenttypeNodeId, sortOrder, text) - VALUES - (@contentTypeId, @sortOrder, @name) - ", - sqlHelper.CreateParameter("@contentTypeId", ContentTypeId), - sqlHelper.CreateParameter("@sortOrder", SortOrder), - sqlHelper.CreateParameter("@name", Name) - ); - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - Id = sqlHelper.ExecuteScalar("SELECT MAX(id) FROM [cmsPropertyTypeGroup]"); - - } - } - - public void Delete() - { - // update all PropertyTypes using this group - foreach (var pt in GetPropertyTypes()) - { - pt.PropertyTypeGroup = 0; - pt.Save(); - } - - foreach (var ptg in GetPropertyTypeGroups()) - ptg.Delete(); - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("DELETE FROM cmsPropertyTypeGroup WHERE id = @id", sqlHelper.CreateParameter("@id", Id)); - } - - internal void Load() - { - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader(@" SELECT contenttypeNodeId, sortOrder, text FROM cmsPropertyTypeGroup WHERE id = @id", sqlHelper.CreateParameter("@id", Id))) - { - if (dr.Read()) - { - SortOrder = dr.GetInt("sortOrder"); - ContentTypeId = dr.GetInt("contenttypeNodeId"); - Name = dr.GetString("text"); - } - } - } - - public static PropertyTypeGroup GetPropertyTypeGroup(int id) - { - var ptg = new PropertyTypeGroup { Id = id }; - ptg.Load(); - return ptg; - } - - public static IEnumerable GetPropertyTypeGroupsFromContentType(int contentTypeId) - { - var ptgs = new List(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (var dr = sqlHelper.ExecuteReader(@" SELECT id FROM cmsPropertyTypeGroup WHERE contenttypeNodeId = @contentTypeId", sqlHelper.CreateParameter("@contentTypeId", contentTypeId))) - { - while (dr.Read()) - { - ptgs.Add(GetPropertyTypeGroup(dr.GetInt("id"))); - } - } - - return ptgs; - } - - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/propertytype/propertytype.cs b/src/umbraco.cms/businesslogic/propertytype/propertytype.cs deleted file mode 100644 index 73ef9cb96d..0000000000 --- a/src/umbraco.cms/businesslogic/propertytype/propertytype.cs +++ /dev/null @@ -1,444 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Threading; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Models; - -using umbraco.BusinessLogic; -using umbraco.cms.businesslogic.web; -using umbraco.DataLayer; -using Umbraco.Core.Composing; -using Language = umbraco.cms.businesslogic.language.Language; - -namespace umbraco.cms.businesslogic.propertytype -{ - /// - /// Summary description for propertytype. - /// - [Obsolete("Use the ContentTypeService instead")] - public class PropertyType - { - #region Declarations - - private readonly int _contenttypeid; - private readonly int _id; - private int _DataTypeId; - private string _alias; - private string _description = ""; - private bool _mandatory; - private string _name; - private int _sortOrder; - private int _tabId; - private int _propertyTypeGroup; - private string _validationRegExp = ""; - - #endregion - - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - - #region Constructors - - public PropertyType(int id) - { - dynamic found; - - using (var scope = Current.ScopeProvider.CreateScope()) - { - found = scope.Database - .SingleOrDefault( - "Select mandatory as mandatory, dataTypeId as dataTypeId, propertyTypeGroupId as propertyTypeGroupId, contentTypeId as contentTypeId, sortOrder as sortOrder, alias as alias, name as name, validationRegExp as validationRegExp, description as description from cmsPropertyType where id=@id", - new { id = id }); - scope.Complete(); - } - - if (found == null) - throw new ArgumentException("Propertytype with id: " + id + " doesnt exist!"); - - _mandatory = found.mandatory; - _id = id; - - if (found.propertyTypeGroupId != null) - { - _propertyTypeGroup = found.propertyTypeGroupId; - //TODO: Remove after refactoring! - _tabId = _propertyTypeGroup; - } - - _sortOrder = found.sortOrder; - _alias = found.alias; - _name = found.name; - _validationRegExp = found.validationRegExp; - _DataTypeId = found.dataTypeId; - _contenttypeid = found.contentTypeId; - _description = found.description; - } - - #endregion - - #region Properties - - - public int Id - { - get { return _id; } - } - - /// - /// Setting the tab id is not meant to be used directly in code. Use the ContentType SetTabOnPropertyType method instead - /// as that will handle all of the caching properly, this will not. - /// - /// - /// Setting the tab id to a negative value will actually set the value to NULL in the database - /// - [Obsolete("Use the new PropertyTypeGroup parameter", false)] - public int TabId - { - get { return _tabId; } - set - { - _tabId = value; - PropertyTypeGroup = value; - } - } - - public int PropertyTypeGroup - { - get { return _propertyTypeGroup; } - set - { - _propertyTypeGroup = value; - object dbPropertyTypeGroup = value; - if (value < 1) - { - dbPropertyTypeGroup = DBNull.Value; - } - - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Update cmsPropertyType set propertyTypeGroupId = @propertyTypeGroupId where id = @id", - sqlHelper.CreateParameter("@propertyTypeGroupId", dbPropertyTypeGroup), - sqlHelper.CreateParameter("@id", Id)); - } - } - - public bool Mandatory - { - get { return _mandatory; } - set - { - _mandatory = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Update cmsPropertyType set mandatory = @mandatory where id = @id", - sqlHelper.CreateParameter("@mandatory", value), - sqlHelper.CreateParameter("@id", Id)); - } - } - - public string ValidationRegExp - { - get { return _validationRegExp; } - set - { - _validationRegExp = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Update cmsPropertyType set validationRegExp = @validationRegExp where id = @id", - sqlHelper.CreateParameter("@validationRegExp", value), sqlHelper.CreateParameter("@id", Id)); - } - } - - public string Description - { - get - { - if (_description != null) - { - if (!_description.StartsWith("#")) - return _description; - else - { - Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); - if (lang != null) - { - - if (Current.Services.LocalizationService.DictionaryItemExists(_description.Substring(1, _description.Length - 1))) - { - var di = Current.Services.LocalizationService.GetDictionaryItemByKey(_description.Substring(1, _description.Length - 1)); - return di.GetTranslatedValue(lang.id); - } - } - } - - return "[" + _description + "]"; - } - - return _description; - } - set - { - _description = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Update cmsPropertyType set description = @description where id = @id", - sqlHelper.CreateParameter("@description", value), - sqlHelper.CreateParameter("@id", Id)); - } - } - - public int SortOrder - { - get { return _sortOrder; } - set - { - _sortOrder = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Update cmsPropertyType set sortOrder = @sortOrder where id = @id", - sqlHelper.CreateParameter("@sortOrder", value), - sqlHelper.CreateParameter("@id", Id)); - } - } - - public string Alias - { - get { return _alias; } - set - { - _alias = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Update cmsPropertyType set alias = @alias where id= @id", - sqlHelper.CreateParameter("@alias", _alias.ToSafeAliasWithForcingCheck()), - sqlHelper.CreateParameter("@id", Id)); - } - } - - public int ContentTypeId - { - get { return _contenttypeid; } - } - - public string Name - { - get - { - if (!_name.StartsWith("#")) - return _name; - else - { - Language lang = Language.GetByCultureCode(Thread.CurrentThread.CurrentCulture.Name); - if (lang != null) - { - - if (Current.Services.LocalizationService.DictionaryItemExists(_name.Substring(1, _name.Length - 1))) - { - var di = Current.Services.LocalizationService.GetDictionaryItemByKey(_name.Substring(1, _name.Length - 1)); - return di.GetTranslatedValue(lang.id); - } - } - - return "[" + _name + "]"; - } - } - set - { - _name = value; - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery( - "UPDATE cmsPropertyType SET name=@name WHERE id=@id", - sqlHelper.CreateParameter("@name", _name), - sqlHelper.CreateParameter("@id", Id)); - } - } - - #endregion - - #region Methods - - public string GetRawName() - { - return _name; - } - - public string GetRawDescription() - { - return _description; - } - - - - public static PropertyType[] GetAll() - { - var result = GetPropertyTypes(); - return result.ToArray(); - } - public static IEnumerable GetPropertyTypes() - { - var result = new List(); - - List propertyTypeIds; - using (var scope = Current.ScopeProvider.CreateScope()) - { - propertyTypeIds = scope.Database.Fetch( - "select id from cmsPropertyType order by Name"); - scope.Complete(); - } - - foreach (var propertyTypeId in propertyTypeIds) - { - PropertyType pt = GetPropertyType(propertyTypeId); - if (pt != null) - result.Add(pt); - } - - return result; - } - - public static IEnumerable GetPropertyTypesByGroup(int groupId, List contentTypeIds) - { - return GetPropertyTypesByGroup(groupId).Where(x => contentTypeIds.Contains(x.ContentTypeId)); - } - - public static IEnumerable GetPropertyTypesByGroup(int groupId) - { - var result = new List(); - - List propertyTypeIds; - using (var scope = Current.ScopeProvider.CreateScope()) - { - propertyTypeIds = scope.Database.Fetch( - "SELECT id FROM cmsPropertyType WHERE propertyTypeGroupId = @groupId order by SortOrder", new { groupId = groupId }); - scope.Complete(); - } - - foreach (var propertyTypeId in propertyTypeIds) - { - PropertyType pt = GetPropertyType(propertyTypeId); - if (pt != null) - result.Add(pt); - } - - return result; - } - - /// - /// Returns all property types based on the data type definition - /// - /// - /// - public static IEnumerable GetByDataTypeDefinition(int dataTypeDefId) - { - var result = new List(); - - List propertyTypeIds; - using (var scope = Current.ScopeProvider.CreateScope()) - { - propertyTypeIds = scope.Database.Fetch( - "select id from cmsPropertyType where dataTypeId=@dataTypeId order by Name", new { dataTypeId = dataTypeDefId }); - scope.Complete(); - } - - foreach (var propertyTypeId in propertyTypeIds) - { - PropertyType pt = GetPropertyType(propertyTypeId); - if (pt != null) - result.Add(pt); - } - - return result; - } - - public void delete() - { - // flush cache - FlushCache(); - - // Delete all properties of propertytype - CleanPropertiesOnDeletion(_contenttypeid); - - //delete tag refs - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Delete from cmsTagRelationship where propertyTypeId = " + Id); - - // Delete PropertyType .. - using (var sqlHelper = LegacySqlHelper.SqlHelper) - sqlHelper.ExecuteNonQuery("Delete from cmsPropertyType where id = " + Id); - - - // delete cache from either master (via tabid) or current contentype - FlushCacheBasedOnTab(); - } - - public void FlushCacheBasedOnTab() - { - if (TabId != 0) - { - ContentType.FlushFromCache(ContentType.Tab.GetTab(TabId).ContentType); - } - else - { - ContentType.FlushFromCache(ContentTypeId); - } - } - - private void CleanPropertiesOnDeletion(int contentTypeId) - { - // first delete from all master document types - //TODO: Verify no endless loops with mixins - DocumentType.GetAllAsList().FindAll(dt => dt.MasterContentTypes.Contains(contentTypeId)).ForEach( - dt => CleanPropertiesOnDeletion(dt.Id)); - - //Initially Content.getContentOfContentType() was called, but because this doesn't include members we resort to sql lookups and deletes - var tmp = new List(); - using (var sqlHelper = LegacySqlHelper.SqlHelper) - using (IRecordsReader dr = sqlHelper.ExecuteReader("SELECT nodeId FROM cmsContent INNER JOIN umbracoNode ON cmsContent.nodeId = umbracoNode.id WHERE ContentType = @contentTypeId ORDER BY umbracoNode.text", sqlHelper.CreateParameter("contentTypeId", contentTypeId))) - { - while (dr.Read()) tmp.Add(dr.GetInt("nodeId")); - - foreach (var contentId in tmp) - { - sqlHelper.ExecuteNonQuery("DELETE FROM cmsPropertyData WHERE PropertyTypeId =" + this.Id + " AND contentNodeId = " + contentId); - } - - // invalidate content type cache - ContentType.FlushFromCache(contentTypeId); - } - } - - - /// - /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility - /// - public virtual void Save() - { - FlushCache(); - } - - protected virtual void FlushCache() - { - // clear cache in contentype - Current.ApplicationCache.RuntimeCache.ClearCacheItem(CacheKeys.ContentTypePropertiesCacheKey + _contenttypeid); - - //Ensure that DocumentTypes are reloaded from db by clearing cache - this similar to the Save method on DocumentType. - //NOTE Would be nice if we could clear cache by type instead of emptying the entire cache. - Current.ApplicationCache.IsolatedRuntimeCache.ClearCache(); - Current.ApplicationCache.IsolatedRuntimeCache.ClearCache(); - Current.ApplicationCache.IsolatedRuntimeCache.ClearCache(); - Current.ApplicationCache.IsolatedRuntimeCache.ClearCache(); - Current.ApplicationCache.IsolatedRuntimeCache.ClearCache(); - Current.ApplicationCache.IsolatedRuntimeCache.ClearCache(); - } - - public static PropertyType GetPropertyType(int id) - { - return new PropertyType(id); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/umbraco.cms/businesslogic/task/Task.cs b/src/umbraco.cms/businesslogic/task/Task.cs deleted file mode 100644 index 13fc055923..0000000000 --- a/src/umbraco.cms/businesslogic/task/Task.cs +++ /dev/null @@ -1,268 +0,0 @@ -using System; -using umbraco.BusinessLogic; -using Umbraco.Core; -using umbraco.DataLayer; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; - -namespace umbraco.cms.businesslogic.task -{ - /// - /// An umbraco task is currently only used with the translation workflow in umbraco. But is extendable to cover other taskbased system as well. - /// A task represent a simple job, it will always be assigned to a user, related to a node, and contain a comment about the task. - /// The user attached to the task can complete the task, and the author of the task can reopen tasks that are not complete correct. - /// - /// Tasks can in umbraco be used for setting up simple workflows, and contains basic controls structures to determine if the task is completed or not. - /// - [Obsolete("Use Umbraco.Core.Service.ITaskService instead")] - public class Task - { - - internal Umbraco.Core.Models.Task TaskEntity; - - #region Properties - - /// - /// Gets or sets the id. - /// - /// The id. - public int Id - { - get { return TaskEntity.Id; } - set { TaskEntity.Id = value; } - } - - /// - /// Gets or sets a value indicating whether this is closed. - /// - /// true if closed; otherwise, false. - public bool Closed - { - get { return TaskEntity.Closed; } - set { TaskEntity.Closed = value; } - } - - - private CMSNode _node; - - /// - /// Gets or sets the node. - /// - /// The node. - public CMSNode Node - { - get { return _node ?? (_node = new CMSNode(TaskEntity.EntityId)); } - set - { - _node = value; - TaskEntity.EntityId = value.Id; - } - } - - private TaskType _type; - - /// - /// Gets or sets the type. - /// - /// The type. - public TaskType Type - { - get { return _type ?? (_type = new TaskType(TaskEntity.TaskType)); } - set - { - _type = value; - TaskEntity.TaskType = new Umbraco.Core.Models.TaskType(_type.Alias) - { - Id = _type.Id - }; - } - } - - - private IUser _parentUser; - - /// - /// Gets or sets the parent user. - /// - /// The parent user. - public IUser ParentUser - { - get { return _parentUser ?? (_parentUser = Current.Services.UserService.GetUserById(TaskEntity.OwnerUserId)); } - set - { - _parentUser = value; - TaskEntity.OwnerUserId = _parentUser.Id; - } - } - - /// - /// Gets or sets the comment. - /// - /// The comment. - public string Comment - { - get { return TaskEntity.Comment; } - set { TaskEntity.Comment = value; } - } - - /// - /// Gets or sets the date. - /// - /// The date. - public DateTime Date - { - get { return TaskEntity.CreateDate; } - set { TaskEntity.CreateDate = value; } - } - - private IUser _user; - - /// - /// Gets or sets the user. - /// - /// The user. - public IUser User - { - get { return _user ?? (_user = Current.Services.UserService.GetUserById(TaskEntity.AssigneeUserId)); } - set - { - _user = value; - TaskEntity.AssigneeUserId = _user.Id; - } - } - - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - public Task() - { - } - - internal Task(Umbraco.Core.Models.Task task) - { - TaskEntity = task; - } - - /// - /// Initializes a new instance of the class. - /// - /// The task id. - public Task(int TaskId) - { - TaskEntity = Current.Services.TaskService.GetTaskById(TaskId); - if (TaskEntity == null) throw new NullReferenceException("No task found with id " + TaskId); - } - - #endregion - - #region Public Methods - - /// - /// Deletes the current task. - /// Generally tasks should not be deleted and closed instead. - /// - public void Delete() - { - Current.Services.TaskService.Delete(TaskEntity); - } - - /// - /// Saves this instance. - /// - public void Save() - { - Current.Services.TaskService.Save(TaskEntity); - } - - #endregion - - #region static methods - - /// - /// Returns all tasks by type - /// - /// - /// - public static Tasks GetTasksByType(int taskType) - { - var foundTaskType = Current.Services.TaskService.GetTaskTypeById(taskType); - if (foundTaskType == null) return null; - - var result = new Tasks(); - var tasks = Current.Services.TaskService.GetTasks(taskTypeAlias: foundTaskType.Alias); - foreach (var task in tasks) - { - result.Add(new Task(task)); - } - - return result; - } - - /// - /// Get all tasks assigned to a node - /// - /// - /// - public static Tasks GetTasks(int nodeId) - { - var result = new Tasks(); - var tasks = Current.Services.TaskService.GetTasks(itemId:nodeId); - foreach (var task in tasks) - { - result.Add(new Task(task)); - } - - return result; - } - - /// - /// Retrieves a collection of open tasks assigned to the user - /// - /// The User who have the tasks assigned - /// If true both open and closed tasks will be returned - /// A collections of tasks - public static Tasks GetTasks(IUser User, bool IncludeClosed) - { - var result = new Tasks(); - var tasks = Current.Services.TaskService.GetTasks(assignedUser:User.Id, includeClosed:IncludeClosed); - foreach (var task in tasks) - { - result.Add(new Task(task)); - } - - return result; - } - - /// - /// Retrieves a collection of open tasks assigned to the user - /// - /// The User who have the tasks assigned - /// If true both open and closed tasks will be returned - /// A collections of tasks - public static Tasks GetOwnedTasks(IUser User, bool IncludeClosed) - { - var result = new Tasks(); - var tasks = Current.Services.TaskService.GetTasks(ownerUser:User.Id, includeClosed: IncludeClosed); - foreach (var task in tasks) - { - result.Add(new Task(task)); - } - return result; - } - - #endregion - } -} diff --git a/src/umbraco.cms/businesslogic/task/TaskType.cs b/src/umbraco.cms/businesslogic/task/TaskType.cs deleted file mode 100644 index 57b2fe1971..0000000000 --- a/src/umbraco.cms/businesslogic/task/TaskType.cs +++ /dev/null @@ -1,123 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Runtime.CompilerServices; - -using umbraco.BusinessLogic; -using Umbraco.Core; -using umbraco.DataLayer; -using Umbraco.Core.Composing; - - -namespace umbraco.cms.businesslogic.task -{ - [Obsolete("Use Umbraco.Core.Service.ITaskService instead")] - public class TaskType - { - internal Umbraco.Core.Models.TaskType TaskTypeEntity; - - #region Public Properties - - public int Id - { - get { return TaskTypeEntity.Id; } - set { TaskTypeEntity.Id = value; } - } - - public string Alias - { - get { return TaskTypeEntity.Alias; } - set { TaskTypeEntity.Alias = value; } - } - - /// - /// All tasks associated with this task type - /// - public Tasks Tasks - { - get - { - //lazy load the tasks - if (_tasks == null) - { - _tasks = Task.GetTasksByType(this.Id); - } - return _tasks; - } - } - - #endregion - - #region Private/protected members - - /// - /// Unused, please do not use - /// - [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] - protected static ISqlHelper SqlHelper - { - get { return LegacySqlHelper.SqlHelper; } - } - - private Tasks _tasks; - - #endregion - - #region Constructors - - internal TaskType(Umbraco.Core.Models.TaskType tt) - { - TaskTypeEntity = tt; - } - - public TaskType() - { - } - - public TaskType(string TypeAlias) - { - TaskTypeEntity = Current.Services.TaskService.GetTaskTypeByAlias(TypeAlias); - if (TaskTypeEntity == null) throw new NullReferenceException("No task type found by alias " + TypeAlias); - } - - public TaskType(int TaskTypeId) - { - TaskTypeEntity = Current.Services.TaskService.GetTaskTypeById(TaskTypeId); - if (TaskTypeEntity == null) throw new NullReferenceException("No task type found by alias " + TaskTypeId); - } - #endregion - - #region Public methods - - public void Save() - { - Current.Services.TaskService.Save(TaskTypeEntity); - } - - /// - /// Deletes the current task type. - /// This will remove all tasks associated with this type - /// - public void Delete() - { - Current.Services.TaskService.Delete(TaskTypeEntity); - } - - #endregion - - #region Static methods - /// - /// Returns all task types stored in the database - /// - /// - public static IEnumerable GetAll() - { - return Current.Services.TaskService.GetAllTaskTypes() - .Select(x => new TaskType(x)); - } - #endregion - - } -} diff --git a/src/umbraco.cms/businesslogic/task/Tasks.cs b/src/umbraco.cms/businesslogic/task/Tasks.cs deleted file mode 100644 index e9e8d50c63..0000000000 --- a/src/umbraco.cms/businesslogic/task/Tasks.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Text; -using System.Runtime.CompilerServices; -using umbraco.BusinessLogic; -using umbraco.DataLayer; - -namespace umbraco.cms.businesslogic.task -{ - /// - /// A collection of tasks. - /// - public class Tasks : CollectionBase - { - /// - /// Adds the specified new task. - /// - /// The new task. - public virtual void Add(Task NewTask) - { - this.List.Add(NewTask); - } - - /// - /// Gets the at the specified index. - /// - /// - public virtual Task this[int Index] - { - get { return (Task)this.List[Index]; } - } - } -} diff --git a/src/umbraco.cms/businesslogic/template/Template.cs b/src/umbraco.cms/businesslogic/template/Template.cs deleted file mode 100644 index 135b0f5a56..0000000000 --- a/src/umbraco.cms/businesslogic/template/Template.cs +++ /dev/null @@ -1,497 +0,0 @@ -using System; -using System.Linq; -using System.Collections; -using System.Xml; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Services; -using System.Text.RegularExpressions; -using System.Collections.Generic; -using umbraco.cms.businesslogic.web; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Xml; - -namespace umbraco.cms.businesslogic.template -{ - /// - /// Summary description for Template. - /// - [Obsolete("Obsolete, Use IFileService and ITemplate to work with templates instead")] - public class Template : CMSNode - { - - #region Private members - - private readonly ViewHelper _viewHelper = new ViewHelper(Current.FileSystems.MvcViewsFileSystem); - private readonly MasterPageHelper _masterPageHelper = new MasterPageHelper(Current.FileSystems.MasterPagesFileSystem); - internal ITemplate TemplateEntity; - private int? _mastertemplate; - - #endregion - - #region Static members - - public static readonly string UmbracoMasterTemplate = SystemDirectories.Umbraco + "/masterpages/default.master"; - private static Hashtable _templateAliases = new Hashtable(); - - #endregion - - - [Obsolete("This is not used at all, do not use this")] - public static Hashtable TemplateAliases - { - get { return _templateAliases; } - set { _templateAliases = value; } - } - - #region Constructors - - internal Template(ITemplate template) - : base(template) - { - TemplateEntity = template; - } - - public Template(int id) : base(id) { } - - public Template(Guid id) : base(id) { } - - #endregion - - /// - /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility - /// - public override void Save() - { - Current.Services.FileService.SaveTemplate(TemplateEntity); - } - - public string GetRawText() - { - return TemplateEntity.Name; - //return base.Text; - } - - //TODO: This is the name of the template, which can apparenlty be localized using the umbraco dictionary, so we need to cater for this but that - // shoud really be done as part of mapping logic for models that are being consumed in the UI, not at the business logic layer. - public override string Text - { - get - { - var tempText = TemplateEntity.Name; - //string tempText = base.Text; - if (!tempText.StartsWith("#")) - return tempText; - else - { - language.Language lang = language.Language.GetByCultureCode(System.Threading.Thread.CurrentThread.CurrentCulture.Name); - if (lang != null) - { - if (Current.Services.LocalizationService.DictionaryItemExists(tempText.Substring(1, tempText.Length - 1))) - { - var di = Current.Services.LocalizationService.GetDictionaryItemByKey(tempText.Substring(1, tempText.Length - 1)); - return di.GetTranslatedValue(lang.id); - } - } - - return "[" + tempText + "]"; - } - } - set - { - FlushCache(); - TemplateEntity.Name = value; - } - } - - [Obsolete("This is not used whatsoever")] - public string OutputContentType { get; set; } - - protected override void setupNode() - { - TemplateEntity = Current.Services.FileService.GetTemplate(Id); - if (TemplateEntity == null) - { - throw new ArgumentException(string.Format("No node exists with id '{0}'", Id)); - } - } - - public new string Path - { - get - { - return TemplateEntity.Path; - } - set - { - TemplateEntity.Path = value; - } - } - - public string Alias - { - get { return TemplateEntity.Alias; } - set { TemplateEntity.Alias = value; } - - } - - public bool HasMasterTemplate - { - get { return (_mastertemplate > 0); } - } - - - public override bool HasChildren - { - get { return TemplateEntity.IsMasterTemplate; } - set - { - //Do nothing! - } - } - - public int MasterTemplate - { - get - { - if (_mastertemplate.HasValue == false) - { - var master = Current.Services.FileService.GetTemplate(TemplateEntity.MasterTemplateAlias); - if (master != null) - { - _mastertemplate = master.Id; - } - else - { - _mastertemplate = -1; - } - } - return _mastertemplate.Value; - } - set - { - //set to null if it's zero - if (value == 0) - { - TemplateEntity.SetMasterTemplate(null); - } - else - { - var found = Current.Services.FileService.GetTemplate(value); - if (found != null) - { - TemplateEntity.SetMasterTemplate(found); - _mastertemplate = found.Id; - } - } - } - } - - public string Design - { - get - { - return TemplateEntity.Content; - } - set - { - TemplateEntity.Content = value; - } - } - - public XmlNode ToXml(XmlDocument doc) - { - var serializer = new EntityXmlSerializer(); - var serialized = serializer.Serialize(TemplateEntity); - return serialized.GetXmlNode(doc); - } - - /// - /// Removes any references to this templates from child templates, documenttypes and documents - /// - public void RemoveAllReferences() - { - if (HasChildren) - { - foreach (var t in GetAllAsList().FindAll(t => t.MasterTemplate == Id)) - { - t.MasterTemplate = 0; - t.Save(); - } - } - - RemoveFromDocumentTypes(); - - // remove from documents - Document.RemoveTemplateFromDocument(this.Id); - - //save it - Save(); - } - - public void RemoveFromDocumentTypes() - { - foreach (DocumentType dt in DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id))) - { - dt.RemoveTemplate(this.Id); - dt.Save(); - } - } - - [Obsolete("This method should have never existed here")] - public IEnumerable GetDocumentTypes() - { - return DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)); - } - - public static Template MakeNew(string Name, IUser u, Template master) - { - return MakeNew(Name, u, master, null); - } - - private static Template MakeNew(string name, IUser u, string design) - { - return MakeNew(name, u, null, design); - } - - public static Template MakeNew(string name, IUser u) - { - return MakeNew(name, u, design: null); - } - - private static Template MakeNew(string name, IUser u, Template master, string design) - { - var foundMaster = master == null ? null : Current.Services.FileService.GetTemplate(master.Id); - var template = Current.Services.FileService.CreateTemplateWithIdentity(name, design, foundMaster, u.Id); - - var legacyTemplate = new Template(template); - - return legacyTemplate; - } - - public static Template GetByAlias(string Alias) - { - return GetByAlias(Alias, false); - } - - [Obsolete("this overload is the same as the other one, the useCache has no affect")] - public static Template GetByAlias(string Alias, bool useCache) - { - var found = Current.Services.FileService.GetTemplate(Alias); - return found == null ? null : new Template(found); - } - - [Obsolete("Obsolete, please use GetAllAsList() method instead", true)] - public static Template[] getAll() - { - return GetAllAsList().ToArray(); - } - - public static List